[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / Parse / ParseDecl.cpp
blob78c3ab72979a007fd81876d27cf49fd004b6eff1
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/Basic/TokenKinds.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/Parse/Parser.h"
24 #include "clang/Parse/RAIIObjectsForParser.h"
25 #include "clang/Sema/EnterExpressionEvaluationContext.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/ParsedTemplate.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/SemaDiagnostic.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringSwitch.h"
33 #include <optional>
35 using namespace clang;
37 //===----------------------------------------------------------------------===//
38 // C99 6.7: Declarations.
39 //===----------------------------------------------------------------------===//
41 /// ParseTypeName
42 /// type-name: [C99 6.7.6]
43 /// specifier-qualifier-list abstract-declarator[opt]
44 ///
45 /// Called type-id in C++.
46 TypeResult Parser::ParseTypeName(SourceRange *Range, DeclaratorContext Context,
47 AccessSpecifier AS, Decl **OwnedType,
48 ParsedAttributes *Attrs) {
49 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
50 if (DSC == DeclSpecContext::DSC_normal)
51 DSC = DeclSpecContext::DSC_type_specifier;
53 // Parse the common declaration-specifiers piece.
54 DeclSpec DS(AttrFactory);
55 if (Attrs)
56 DS.addAttributes(*Attrs);
57 ParseSpecifierQualifierList(DS, AS, DSC);
58 if (OwnedType)
59 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
61 // Move declspec attributes to ParsedAttributes
62 if (Attrs) {
63 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
64 for (ParsedAttr &AL : DS.getAttributes()) {
65 if (AL.isDeclspecAttribute())
66 ToBeMoved.push_back(&AL);
69 for (ParsedAttr *AL : ToBeMoved)
70 Attrs->takeOneFrom(DS.getAttributes(), AL);
73 // Parse the abstract-declarator, if present.
74 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
75 ParseDeclarator(DeclaratorInfo);
76 if (Range)
77 *Range = DeclaratorInfo.getSourceRange();
79 if (DeclaratorInfo.isInvalidType())
80 return true;
82 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
85 /// Normalizes an attribute name by dropping prefixed and suffixed __.
86 static StringRef normalizeAttrName(StringRef Name) {
87 if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
88 return Name.drop_front(2).drop_back(2);
89 return Name;
92 /// isAttributeLateParsed - Return true if the attribute has arguments that
93 /// require late parsing.
94 static bool isAttributeLateParsed(const IdentifierInfo &II) {
95 #define CLANG_ATTR_LATE_PARSED_LIST
96 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
97 #include "clang/Parse/AttrParserStringSwitches.inc"
98 .Default(false);
99 #undef CLANG_ATTR_LATE_PARSED_LIST
102 /// Check if the a start and end source location expand to the same macro.
103 static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
104 SourceLocation EndLoc) {
105 if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
106 return false;
108 SourceManager &SM = PP.getSourceManager();
109 if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
110 return false;
112 bool AttrStartIsInMacro =
113 Lexer::isAtStartOfMacroExpansion(StartLoc, SM, PP.getLangOpts());
114 bool AttrEndIsInMacro =
115 Lexer::isAtEndOfMacroExpansion(EndLoc, SM, PP.getLangOpts());
116 return AttrStartIsInMacro && AttrEndIsInMacro;
119 void Parser::ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
120 LateParsedAttrList *LateAttrs) {
121 bool MoreToParse;
122 do {
123 // Assume there's nothing left to parse, but if any attributes are in fact
124 // parsed, loop to ensure all specified attribute combinations are parsed.
125 MoreToParse = false;
126 if (WhichAttrKinds & PAKM_CXX11)
127 MoreToParse |= MaybeParseCXX11Attributes(Attrs);
128 if (WhichAttrKinds & PAKM_GNU)
129 MoreToParse |= MaybeParseGNUAttributes(Attrs, LateAttrs);
130 if (WhichAttrKinds & PAKM_Declspec)
131 MoreToParse |= MaybeParseMicrosoftDeclSpecs(Attrs);
132 } while (MoreToParse);
135 /// ParseGNUAttributes - Parse a non-empty attributes list.
137 /// [GNU] attributes:
138 /// attribute
139 /// attributes attribute
141 /// [GNU] attribute:
142 /// '__attribute__' '(' '(' attribute-list ')' ')'
144 /// [GNU] attribute-list:
145 /// attrib
146 /// attribute_list ',' attrib
148 /// [GNU] attrib:
149 /// empty
150 /// attrib-name
151 /// attrib-name '(' identifier ')'
152 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
153 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
155 /// [GNU] attrib-name:
156 /// identifier
157 /// typespec
158 /// typequal
159 /// storageclass
161 /// Whether an attribute takes an 'identifier' is determined by the
162 /// attrib-name. GCC's behavior here is not worth imitating:
164 /// * In C mode, if the attribute argument list starts with an identifier
165 /// followed by a ',' or an ')', and the identifier doesn't resolve to
166 /// a type, it is parsed as an identifier. If the attribute actually
167 /// wanted an expression, it's out of luck (but it turns out that no
168 /// attributes work that way, because C constant expressions are very
169 /// limited).
170 /// * In C++ mode, if the attribute argument list starts with an identifier,
171 /// and the attribute *wants* an identifier, it is parsed as an identifier.
172 /// At block scope, any additional tokens between the identifier and the
173 /// ',' or ')' are ignored, otherwise they produce a parse error.
175 /// We follow the C++ model, but don't allow junk after the identifier.
176 void Parser::ParseGNUAttributes(ParsedAttributes &Attrs,
177 LateParsedAttrList *LateAttrs, Declarator *D) {
178 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
180 SourceLocation StartLoc = Tok.getLocation();
181 SourceLocation EndLoc = StartLoc;
183 while (Tok.is(tok::kw___attribute)) {
184 SourceLocation AttrTokLoc = ConsumeToken();
185 unsigned OldNumAttrs = Attrs.size();
186 unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
188 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
189 "attribute")) {
190 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
191 return;
193 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
194 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
195 return;
197 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
198 do {
199 // Eat preceeding commas to allow __attribute__((,,,foo))
200 while (TryConsumeToken(tok::comma))
203 // Expect an identifier or declaration specifier (const, int, etc.)
204 if (Tok.isAnnotation())
205 break;
206 if (Tok.is(tok::code_completion)) {
207 cutOffParsing();
208 Actions.CodeCompleteAttribute(AttributeCommonInfo::Syntax::AS_GNU);
209 break;
211 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
212 if (!AttrName)
213 break;
215 SourceLocation AttrNameLoc = ConsumeToken();
217 if (Tok.isNot(tok::l_paren)) {
218 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
219 ParsedAttr::Form::GNU());
220 continue;
223 // Handle "parameterized" attributes
224 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
225 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr,
226 SourceLocation(), ParsedAttr::Form::GNU(), D);
227 continue;
230 // Handle attributes with arguments that require late parsing.
231 LateParsedAttribute *LA =
232 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
233 LateAttrs->push_back(LA);
235 // Attributes in a class are parsed at the end of the class, along
236 // with other late-parsed declarations.
237 if (!ClassStack.empty() && !LateAttrs->parseSoon())
238 getCurrentClass().LateParsedDeclarations.push_back(LA);
240 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
241 // recursively consumes balanced parens.
242 LA->Toks.push_back(Tok);
243 ConsumeParen();
244 // Consume everything up to and including the matching right parens.
245 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
247 Token Eof;
248 Eof.startToken();
249 Eof.setLocation(Tok.getLocation());
250 LA->Toks.push_back(Eof);
251 } while (Tok.is(tok::comma));
253 if (ExpectAndConsume(tok::r_paren))
254 SkipUntil(tok::r_paren, StopAtSemi);
255 SourceLocation Loc = Tok.getLocation();
256 if (ExpectAndConsume(tok::r_paren))
257 SkipUntil(tok::r_paren, StopAtSemi);
258 EndLoc = Loc;
260 // If this was declared in a macro, attach the macro IdentifierInfo to the
261 // parsed attribute.
262 auto &SM = PP.getSourceManager();
263 if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
264 FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
265 CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
266 StringRef FoundName =
267 Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
268 IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
270 for (unsigned i = OldNumAttrs; i < Attrs.size(); ++i)
271 Attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
273 if (LateAttrs) {
274 for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
275 (*LateAttrs)[i]->MacroII = MacroII;
280 Attrs.Range = SourceRange(StartLoc, EndLoc);
283 /// Determine whether the given attribute has an identifier argument.
284 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
285 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
286 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
287 #include "clang/Parse/AttrParserStringSwitches.inc"
288 .Default(false);
289 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
292 /// Determine whether the given attribute has an identifier argument.
293 static ParsedAttributeArgumentsProperties
294 attributeStringLiteralListArg(const IdentifierInfo &II) {
295 #define CLANG_ATTR_STRING_LITERAL_ARG_LIST
296 return llvm::StringSwitch<uint32_t>(normalizeAttrName(II.getName()))
297 #include "clang/Parse/AttrParserStringSwitches.inc"
298 .Default(0);
299 #undef CLANG_ATTR_STRING_LITERAL_ARG_LIST
302 /// Determine whether the given attribute has a variadic identifier argument.
303 static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
304 #define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
305 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
306 #include "clang/Parse/AttrParserStringSwitches.inc"
307 .Default(false);
308 #undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
311 /// Determine whether the given attribute treats kw_this as an identifier.
312 static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
313 #define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
314 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
315 #include "clang/Parse/AttrParserStringSwitches.inc"
316 .Default(false);
317 #undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
320 /// Determine if an attribute accepts parameter packs.
321 static bool attributeAcceptsExprPack(const IdentifierInfo &II) {
322 #define CLANG_ATTR_ACCEPTS_EXPR_PACK
323 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
324 #include "clang/Parse/AttrParserStringSwitches.inc"
325 .Default(false);
326 #undef CLANG_ATTR_ACCEPTS_EXPR_PACK
329 /// Determine whether the given attribute parses a type argument.
330 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
331 #define CLANG_ATTR_TYPE_ARG_LIST
332 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
333 #include "clang/Parse/AttrParserStringSwitches.inc"
334 .Default(false);
335 #undef CLANG_ATTR_TYPE_ARG_LIST
338 /// Determine whether the given attribute requires parsing its arguments
339 /// in an unevaluated context or not.
340 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
341 #define CLANG_ATTR_ARG_CONTEXT_LIST
342 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
343 #include "clang/Parse/AttrParserStringSwitches.inc"
344 .Default(false);
345 #undef CLANG_ATTR_ARG_CONTEXT_LIST
348 IdentifierLoc *Parser::ParseIdentifierLoc() {
349 assert(Tok.is(tok::identifier) && "expected an identifier");
350 IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
351 Tok.getLocation(),
352 Tok.getIdentifierInfo());
353 ConsumeToken();
354 return IL;
357 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
358 SourceLocation AttrNameLoc,
359 ParsedAttributes &Attrs,
360 IdentifierInfo *ScopeName,
361 SourceLocation ScopeLoc,
362 ParsedAttr::Form Form) {
363 BalancedDelimiterTracker Parens(*this, tok::l_paren);
364 Parens.consumeOpen();
366 TypeResult T;
367 if (Tok.isNot(tok::r_paren))
368 T = ParseTypeName();
370 if (Parens.consumeClose())
371 return;
373 if (T.isInvalid())
374 return;
376 if (T.isUsable())
377 Attrs.addNewTypeAttr(&AttrName,
378 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
379 ScopeName, ScopeLoc, T.get(), Form);
380 else
381 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
382 ScopeName, ScopeLoc, nullptr, 0, Form);
385 ExprResult
386 Parser::ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName) {
387 if (Tok.is(tok::l_paren)) {
388 BalancedDelimiterTracker Paren(*this, tok::l_paren);
389 Paren.consumeOpen();
390 ExprResult Res = ParseUnevaluatedStringInAttribute(AttrName);
391 Paren.consumeClose();
392 return Res;
394 if (!isTokenStringLiteral()) {
395 Diag(Tok.getLocation(), diag::err_expected_string_literal)
396 << /*in attribute...*/ 4 << AttrName.getName();
397 return ExprError();
399 return ParseUnevaluatedStringLiteralExpression();
402 bool Parser::ParseAttributeArgumentList(
403 const IdentifierInfo &AttrName, SmallVectorImpl<Expr *> &Exprs,
404 ParsedAttributeArgumentsProperties ArgsProperties) {
405 bool SawError = false;
406 unsigned Arg = 0;
407 while (true) {
408 ExprResult Expr;
409 if (ArgsProperties.isStringLiteralArg(Arg)) {
410 Expr = ParseUnevaluatedStringInAttribute(AttrName);
411 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
412 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
413 Expr = ParseBraceInitializer();
414 } else {
415 Expr = ParseAssignmentExpression();
417 Expr = Actions.CorrectDelayedTyposInExpr(Expr);
419 if (Tok.is(tok::ellipsis))
420 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
421 else if (Tok.is(tok::code_completion)) {
422 // There's nothing to suggest in here as we parsed a full expression.
423 // Instead fail and propagate the error since caller might have something
424 // the suggest, e.g. signature help in function call. Note that this is
425 // performed before pushing the \p Expr, so that signature help can report
426 // current argument correctly.
427 SawError = true;
428 cutOffParsing();
429 break;
432 if (Expr.isInvalid()) {
433 SawError = true;
434 break;
437 Exprs.push_back(Expr.get());
439 if (Tok.isNot(tok::comma))
440 break;
441 // Move to the next argument, remember where the comma was.
442 Token Comma = Tok;
443 ConsumeToken();
444 checkPotentialAngleBracketDelimiter(Comma);
445 Arg++;
448 if (SawError) {
449 // Ensure typos get diagnosed when errors were encountered while parsing the
450 // expression list.
451 for (auto &E : Exprs) {
452 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
453 if (Expr.isUsable())
454 E = Expr.get();
457 return SawError;
460 unsigned Parser::ParseAttributeArgsCommon(
461 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
462 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
463 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
464 // Ignore the left paren location for now.
465 ConsumeParen();
467 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
468 bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
469 bool AttributeHasVariadicIdentifierArg =
470 attributeHasVariadicIdentifierArg(*AttrName);
472 // Interpret "kw_this" as an identifier if the attributed requests it.
473 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
474 Tok.setKind(tok::identifier);
476 ArgsVector ArgExprs;
477 if (Tok.is(tok::identifier)) {
478 // If this attribute wants an 'identifier' argument, make it so.
479 bool IsIdentifierArg = AttributeHasVariadicIdentifierArg ||
480 attributeHasIdentifierArg(*AttrName);
481 ParsedAttr::Kind AttrKind =
482 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
484 // If we don't know how to parse this attribute, but this is the only
485 // token in this argument, assume it's meant to be an identifier.
486 if (AttrKind == ParsedAttr::UnknownAttribute ||
487 AttrKind == ParsedAttr::IgnoredAttribute) {
488 const Token &Next = NextToken();
489 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
492 if (IsIdentifierArg)
493 ArgExprs.push_back(ParseIdentifierLoc());
496 ParsedType TheParsedType;
497 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
498 // Eat the comma.
499 if (!ArgExprs.empty())
500 ConsumeToken();
502 if (AttributeIsTypeArgAttr) {
503 // FIXME: Multiple type arguments are not implemented.
504 TypeResult T = ParseTypeName();
505 if (T.isInvalid()) {
506 SkipUntil(tok::r_paren, StopAtSemi);
507 return 0;
509 if (T.isUsable())
510 TheParsedType = T.get();
511 } else if (AttributeHasVariadicIdentifierArg) {
512 // Parse variadic identifier arg. This can either consume identifiers or
513 // expressions. Variadic identifier args do not support parameter packs
514 // because those are typically used for attributes with enumeration
515 // arguments, and those enumerations are not something the user could
516 // express via a pack.
517 do {
518 // Interpret "kw_this" as an identifier if the attributed requests it.
519 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
520 Tok.setKind(tok::identifier);
522 ExprResult ArgExpr;
523 if (Tok.is(tok::identifier)) {
524 ArgExprs.push_back(ParseIdentifierLoc());
525 } else {
526 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
527 EnterExpressionEvaluationContext Unevaluated(
528 Actions,
529 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
530 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
532 ExprResult ArgExpr(
533 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
535 if (ArgExpr.isInvalid()) {
536 SkipUntil(tok::r_paren, StopAtSemi);
537 return 0;
539 ArgExprs.push_back(ArgExpr.get());
541 // Eat the comma, move to the next argument
542 } while (TryConsumeToken(tok::comma));
543 } else {
544 // General case. Parse all available expressions.
545 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
546 EnterExpressionEvaluationContext Unevaluated(
547 Actions, Uneval
548 ? Sema::ExpressionEvaluationContext::Unevaluated
549 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
551 ExprVector ParsedExprs;
552 ParsedAttributeArgumentsProperties ArgProperties =
553 attributeStringLiteralListArg(*AttrName);
554 if (ParseAttributeArgumentList(*AttrName, ParsedExprs, ArgProperties)) {
555 SkipUntil(tok::r_paren, StopAtSemi);
556 return 0;
559 // Pack expansion must currently be explicitly supported by an attribute.
560 for (size_t I = 0; I < ParsedExprs.size(); ++I) {
561 if (!isa<PackExpansionExpr>(ParsedExprs[I]))
562 continue;
564 if (!attributeAcceptsExprPack(*AttrName)) {
565 Diag(Tok.getLocation(),
566 diag::err_attribute_argument_parm_pack_not_supported)
567 << AttrName;
568 SkipUntil(tok::r_paren, StopAtSemi);
569 return 0;
573 ArgExprs.insert(ArgExprs.end(), ParsedExprs.begin(), ParsedExprs.end());
577 SourceLocation RParen = Tok.getLocation();
578 if (!ExpectAndConsume(tok::r_paren)) {
579 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
581 if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
582 Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
583 ScopeName, ScopeLoc, TheParsedType, Form);
584 } else {
585 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
586 ArgExprs.data(), ArgExprs.size(), Form);
590 if (EndLoc)
591 *EndLoc = RParen;
593 return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
596 /// Parse the arguments to a parameterized GNU attribute or
597 /// a C++11 attribute in "gnu" namespace.
598 void Parser::ParseGNUAttributeArgs(
599 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
600 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
601 SourceLocation ScopeLoc, ParsedAttr::Form Form, Declarator *D) {
603 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
605 ParsedAttr::Kind AttrKind =
606 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
608 if (AttrKind == ParsedAttr::AT_Availability) {
609 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
610 ScopeLoc, Form);
611 return;
612 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
613 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
614 ScopeName, ScopeLoc, Form);
615 return;
616 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
617 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
618 ScopeName, ScopeLoc, Form);
619 return;
620 } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
621 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
622 ScopeLoc, Form);
623 return;
624 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
625 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
626 ScopeName, ScopeLoc, Form);
627 return;
628 } else if (attributeIsTypeArgAttr(*AttrName)) {
629 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, ScopeName,
630 ScopeLoc, Form);
631 return;
634 // These may refer to the function arguments, but need to be parsed early to
635 // participate in determining whether it's a redeclaration.
636 std::optional<ParseScope> PrototypeScope;
637 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
638 D && D->isFunctionDeclarator()) {
639 DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
640 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
641 Scope::FunctionDeclarationScope |
642 Scope::DeclScope);
643 for (unsigned i = 0; i != FTI.NumParams; ++i) {
644 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
645 Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
649 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
650 ScopeLoc, Form);
653 unsigned Parser::ParseClangAttributeArgs(
654 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
655 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
656 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
657 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
659 ParsedAttr::Kind AttrKind =
660 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
662 switch (AttrKind) {
663 default:
664 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
665 ScopeName, ScopeLoc, Form);
666 case ParsedAttr::AT_ExternalSourceSymbol:
667 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
668 ScopeName, ScopeLoc, Form);
669 break;
670 case ParsedAttr::AT_Availability:
671 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
672 ScopeLoc, Form);
673 break;
674 case ParsedAttr::AT_ObjCBridgeRelated:
675 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
676 ScopeName, ScopeLoc, Form);
677 break;
678 case ParsedAttr::AT_SwiftNewType:
679 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
680 ScopeLoc, Form);
681 break;
682 case ParsedAttr::AT_TypeTagForDatatype:
683 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
684 ScopeName, ScopeLoc, Form);
685 break;
687 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
690 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
691 SourceLocation AttrNameLoc,
692 ParsedAttributes &Attrs) {
693 unsigned ExistingAttrs = Attrs.size();
695 // If the attribute isn't known, we will not attempt to parse any
696 // arguments.
697 if (!hasAttribute(AttributeCommonInfo::Syntax::AS_Declspec, nullptr, AttrName,
698 getTargetInfo(), getLangOpts())) {
699 // Eat the left paren, then skip to the ending right paren.
700 ConsumeParen();
701 SkipUntil(tok::r_paren);
702 return false;
705 SourceLocation OpenParenLoc = Tok.getLocation();
707 if (AttrName->getName() == "property") {
708 // The property declspec is more complex in that it can take one or two
709 // assignment expressions as a parameter, but the lhs of the assignment
710 // must be named get or put.
712 BalancedDelimiterTracker T(*this, tok::l_paren);
713 T.expectAndConsume(diag::err_expected_lparen_after,
714 AttrName->getNameStart(), tok::r_paren);
716 enum AccessorKind {
717 AK_Invalid = -1,
718 AK_Put = 0,
719 AK_Get = 1 // indices into AccessorNames
721 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
722 bool HasInvalidAccessor = false;
724 // Parse the accessor specifications.
725 while (true) {
726 // Stop if this doesn't look like an accessor spec.
727 if (!Tok.is(tok::identifier)) {
728 // If the user wrote a completely empty list, use a special diagnostic.
729 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
730 AccessorNames[AK_Put] == nullptr &&
731 AccessorNames[AK_Get] == nullptr) {
732 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
733 break;
736 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
737 break;
740 AccessorKind Kind;
741 SourceLocation KindLoc = Tok.getLocation();
742 StringRef KindStr = Tok.getIdentifierInfo()->getName();
743 if (KindStr == "get") {
744 Kind = AK_Get;
745 } else if (KindStr == "put") {
746 Kind = AK_Put;
748 // Recover from the common mistake of using 'set' instead of 'put'.
749 } else if (KindStr == "set") {
750 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
751 << FixItHint::CreateReplacement(KindLoc, "put");
752 Kind = AK_Put;
754 // Handle the mistake of forgetting the accessor kind by skipping
755 // this accessor.
756 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
757 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
758 ConsumeToken();
759 HasInvalidAccessor = true;
760 goto next_property_accessor;
762 // Otherwise, complain about the unknown accessor kind.
763 } else {
764 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
765 HasInvalidAccessor = true;
766 Kind = AK_Invalid;
768 // Try to keep parsing unless it doesn't look like an accessor spec.
769 if (!NextToken().is(tok::equal))
770 break;
773 // Consume the identifier.
774 ConsumeToken();
776 // Consume the '='.
777 if (!TryConsumeToken(tok::equal)) {
778 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
779 << KindStr;
780 break;
783 // Expect the method name.
784 if (!Tok.is(tok::identifier)) {
785 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
786 break;
789 if (Kind == AK_Invalid) {
790 // Just drop invalid accessors.
791 } else if (AccessorNames[Kind] != nullptr) {
792 // Complain about the repeated accessor, ignore it, and keep parsing.
793 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
794 } else {
795 AccessorNames[Kind] = Tok.getIdentifierInfo();
797 ConsumeToken();
799 next_property_accessor:
800 // Keep processing accessors until we run out.
801 if (TryConsumeToken(tok::comma))
802 continue;
804 // If we run into the ')', stop without consuming it.
805 if (Tok.is(tok::r_paren))
806 break;
808 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
809 break;
812 // Only add the property attribute if it was well-formed.
813 if (!HasInvalidAccessor)
814 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
815 AccessorNames[AK_Get], AccessorNames[AK_Put],
816 ParsedAttr::Form::Declspec());
817 T.skipToEnd();
818 return !HasInvalidAccessor;
821 unsigned NumArgs =
822 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
823 SourceLocation(), ParsedAttr::Form::Declspec());
825 // If this attribute's args were parsed, and it was expected to have
826 // arguments but none were provided, emit a diagnostic.
827 if (ExistingAttrs < Attrs.size() && Attrs.back().getMaxArgs() && !NumArgs) {
828 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
829 return false;
831 return true;
834 /// [MS] decl-specifier:
835 /// __declspec ( extended-decl-modifier-seq )
837 /// [MS] extended-decl-modifier-seq:
838 /// extended-decl-modifier[opt]
839 /// extended-decl-modifier extended-decl-modifier-seq
840 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
841 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
842 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
844 SourceLocation StartLoc = Tok.getLocation();
845 SourceLocation EndLoc = StartLoc;
847 while (Tok.is(tok::kw___declspec)) {
848 ConsumeToken();
849 BalancedDelimiterTracker T(*this, tok::l_paren);
850 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
851 tok::r_paren))
852 return;
854 // An empty declspec is perfectly legal and should not warn. Additionally,
855 // you can specify multiple attributes per declspec.
856 while (Tok.isNot(tok::r_paren)) {
857 // Attribute not present.
858 if (TryConsumeToken(tok::comma))
859 continue;
861 if (Tok.is(tok::code_completion)) {
862 cutOffParsing();
863 Actions.CodeCompleteAttribute(AttributeCommonInfo::AS_Declspec);
864 return;
867 // We expect either a well-known identifier or a generic string. Anything
868 // else is a malformed declspec.
869 bool IsString = Tok.getKind() == tok::string_literal;
870 if (!IsString && Tok.getKind() != tok::identifier &&
871 Tok.getKind() != tok::kw_restrict) {
872 Diag(Tok, diag::err_ms_declspec_type);
873 T.skipToEnd();
874 return;
877 IdentifierInfo *AttrName;
878 SourceLocation AttrNameLoc;
879 if (IsString) {
880 SmallString<8> StrBuffer;
881 bool Invalid = false;
882 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
883 if (Invalid) {
884 T.skipToEnd();
885 return;
887 AttrName = PP.getIdentifierInfo(Str);
888 AttrNameLoc = ConsumeStringToken();
889 } else {
890 AttrName = Tok.getIdentifierInfo();
891 AttrNameLoc = ConsumeToken();
894 bool AttrHandled = false;
896 // Parse attribute arguments.
897 if (Tok.is(tok::l_paren))
898 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
899 else if (AttrName->getName() == "property")
900 // The property attribute must have an argument list.
901 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
902 << AttrName->getName();
904 if (!AttrHandled)
905 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
906 ParsedAttr::Form::Declspec());
908 T.consumeClose();
909 EndLoc = T.getCloseLocation();
912 Attrs.Range = SourceRange(StartLoc, EndLoc);
915 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
916 // Treat these like attributes
917 while (true) {
918 auto Kind = Tok.getKind();
919 switch (Kind) {
920 case tok::kw___fastcall:
921 case tok::kw___stdcall:
922 case tok::kw___thiscall:
923 case tok::kw___regcall:
924 case tok::kw___cdecl:
925 case tok::kw___vectorcall:
926 case tok::kw___ptr64:
927 case tok::kw___w64:
928 case tok::kw___ptr32:
929 case tok::kw___sptr:
930 case tok::kw___uptr: {
931 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
932 SourceLocation AttrNameLoc = ConsumeToken();
933 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
934 Kind);
935 break;
937 default:
938 return;
943 void Parser::ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &attrs) {
944 assert(Tok.is(tok::kw___funcref));
945 SourceLocation StartLoc = Tok.getLocation();
946 if (!getTargetInfo().getTriple().isWasm()) {
947 ConsumeToken();
948 Diag(StartLoc, diag::err_wasm_funcref_not_wasm);
949 return;
952 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
953 SourceLocation AttrNameLoc = ConsumeToken();
954 attrs.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
955 /*ScopeLoc=*/SourceLocation{}, /*Args=*/nullptr, /*numArgs=*/0,
956 tok::kw___funcref);
959 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
960 SourceLocation StartLoc = Tok.getLocation();
961 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
963 if (EndLoc.isValid()) {
964 SourceRange Range(StartLoc, EndLoc);
965 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
969 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
970 SourceLocation EndLoc;
972 while (true) {
973 switch (Tok.getKind()) {
974 case tok::kw_const:
975 case tok::kw_volatile:
976 case tok::kw___fastcall:
977 case tok::kw___stdcall:
978 case tok::kw___thiscall:
979 case tok::kw___cdecl:
980 case tok::kw___vectorcall:
981 case tok::kw___ptr32:
982 case tok::kw___ptr64:
983 case tok::kw___w64:
984 case tok::kw___unaligned:
985 case tok::kw___sptr:
986 case tok::kw___uptr:
987 EndLoc = ConsumeToken();
988 break;
989 default:
990 return EndLoc;
995 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
996 // Treat these like attributes
997 while (Tok.is(tok::kw___pascal)) {
998 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
999 SourceLocation AttrNameLoc = ConsumeToken();
1000 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1001 tok::kw___pascal);
1005 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
1006 // Treat these like attributes
1007 while (Tok.is(tok::kw___kernel)) {
1008 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1009 SourceLocation AttrNameLoc = ConsumeToken();
1010 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1011 tok::kw___kernel);
1015 void Parser::ParseCUDAFunctionAttributes(ParsedAttributes &attrs) {
1016 while (Tok.is(tok::kw___noinline__)) {
1017 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1018 SourceLocation AttrNameLoc = ConsumeToken();
1019 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1020 tok::kw___noinline__);
1024 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
1025 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1026 SourceLocation AttrNameLoc = Tok.getLocation();
1027 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1028 Tok.getKind());
1031 bool Parser::isHLSLQualifier(const Token &Tok) const {
1032 return Tok.is(tok::kw_groupshared);
1035 void Parser::ParseHLSLQualifiers(ParsedAttributes &Attrs) {
1036 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1037 auto Kind = Tok.getKind();
1038 SourceLocation AttrNameLoc = ConsumeToken();
1039 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, Kind);
1042 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
1043 // Treat these like attributes, even though they're type specifiers.
1044 while (true) {
1045 auto Kind = Tok.getKind();
1046 switch (Kind) {
1047 case tok::kw__Nonnull:
1048 case tok::kw__Nullable:
1049 case tok::kw__Nullable_result:
1050 case tok::kw__Null_unspecified: {
1051 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1052 SourceLocation AttrNameLoc = ConsumeToken();
1053 if (!getLangOpts().ObjC)
1054 Diag(AttrNameLoc, diag::ext_nullability)
1055 << AttrName;
1056 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1057 Kind);
1058 break;
1060 default:
1061 return;
1066 static bool VersionNumberSeparator(const char Separator) {
1067 return (Separator == '.' || Separator == '_');
1070 /// Parse a version number.
1072 /// version:
1073 /// simple-integer
1074 /// simple-integer '.' simple-integer
1075 /// simple-integer '_' simple-integer
1076 /// simple-integer '.' simple-integer '.' simple-integer
1077 /// simple-integer '_' simple-integer '_' simple-integer
1078 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
1079 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
1081 if (!Tok.is(tok::numeric_constant)) {
1082 Diag(Tok, diag::err_expected_version);
1083 SkipUntil(tok::comma, tok::r_paren,
1084 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1085 return VersionTuple();
1088 // Parse the major (and possibly minor and subminor) versions, which
1089 // are stored in the numeric constant. We utilize a quirk of the
1090 // lexer, which is that it handles something like 1.2.3 as a single
1091 // numeric constant, rather than two separate tokens.
1092 SmallString<512> Buffer;
1093 Buffer.resize(Tok.getLength()+1);
1094 const char *ThisTokBegin = &Buffer[0];
1096 // Get the spelling of the token, which eliminates trigraphs, etc.
1097 bool Invalid = false;
1098 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1099 if (Invalid)
1100 return VersionTuple();
1102 // Parse the major version.
1103 unsigned AfterMajor = 0;
1104 unsigned Major = 0;
1105 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
1106 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
1107 ++AfterMajor;
1110 if (AfterMajor == 0) {
1111 Diag(Tok, diag::err_expected_version);
1112 SkipUntil(tok::comma, tok::r_paren,
1113 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1114 return VersionTuple();
1117 if (AfterMajor == ActualLength) {
1118 ConsumeToken();
1120 // We only had a single version component.
1121 if (Major == 0) {
1122 Diag(Tok, diag::err_zero_version);
1123 return VersionTuple();
1126 return VersionTuple(Major);
1129 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
1130 if (!VersionNumberSeparator(AfterMajorSeparator)
1131 || (AfterMajor + 1 == ActualLength)) {
1132 Diag(Tok, diag::err_expected_version);
1133 SkipUntil(tok::comma, tok::r_paren,
1134 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1135 return VersionTuple();
1138 // Parse the minor version.
1139 unsigned AfterMinor = AfterMajor + 1;
1140 unsigned Minor = 0;
1141 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
1142 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
1143 ++AfterMinor;
1146 if (AfterMinor == ActualLength) {
1147 ConsumeToken();
1149 // We had major.minor.
1150 if (Major == 0 && Minor == 0) {
1151 Diag(Tok, diag::err_zero_version);
1152 return VersionTuple();
1155 return VersionTuple(Major, Minor);
1158 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
1159 // If what follows is not a '.' or '_', we have a problem.
1160 if (!VersionNumberSeparator(AfterMinorSeparator)) {
1161 Diag(Tok, diag::err_expected_version);
1162 SkipUntil(tok::comma, tok::r_paren,
1163 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1164 return VersionTuple();
1167 // Warn if separators, be it '.' or '_', do not match.
1168 if (AfterMajorSeparator != AfterMinorSeparator)
1169 Diag(Tok, diag::warn_expected_consistent_version_separator);
1171 // Parse the subminor version.
1172 unsigned AfterSubminor = AfterMinor + 1;
1173 unsigned Subminor = 0;
1174 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
1175 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
1176 ++AfterSubminor;
1179 if (AfterSubminor != ActualLength) {
1180 Diag(Tok, diag::err_expected_version);
1181 SkipUntil(tok::comma, tok::r_paren,
1182 StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1183 return VersionTuple();
1185 ConsumeToken();
1186 return VersionTuple(Major, Minor, Subminor);
1189 /// Parse the contents of the "availability" attribute.
1191 /// availability-attribute:
1192 /// 'availability' '(' platform ',' opt-strict version-arg-list,
1193 /// opt-replacement, opt-message')'
1195 /// platform:
1196 /// identifier
1198 /// opt-strict:
1199 /// 'strict' ','
1201 /// version-arg-list:
1202 /// version-arg
1203 /// version-arg ',' version-arg-list
1205 /// version-arg:
1206 /// 'introduced' '=' version
1207 /// 'deprecated' '=' version
1208 /// 'obsoleted' = version
1209 /// 'unavailable'
1210 /// opt-replacement:
1211 /// 'replacement' '=' <string>
1212 /// opt-message:
1213 /// 'message' '=' <string>
1214 void Parser::ParseAvailabilityAttribute(
1215 IdentifierInfo &Availability, SourceLocation AvailabilityLoc,
1216 ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName,
1217 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1218 enum { Introduced, Deprecated, Obsoleted, Unknown };
1219 AvailabilityChange Changes[Unknown];
1220 ExprResult MessageExpr, ReplacementExpr;
1222 // Opening '('.
1223 BalancedDelimiterTracker T(*this, tok::l_paren);
1224 if (T.consumeOpen()) {
1225 Diag(Tok, diag::err_expected) << tok::l_paren;
1226 return;
1229 // Parse the platform name.
1230 if (Tok.isNot(tok::identifier)) {
1231 Diag(Tok, diag::err_availability_expected_platform);
1232 SkipUntil(tok::r_paren, StopAtSemi);
1233 return;
1235 IdentifierLoc *Platform = ParseIdentifierLoc();
1236 if (const IdentifierInfo *const Ident = Platform->Ident) {
1237 // Canonicalize platform name from "macosx" to "macos".
1238 if (Ident->getName() == "macosx")
1239 Platform->Ident = PP.getIdentifierInfo("macos");
1240 // Canonicalize platform name from "macosx_app_extension" to
1241 // "macos_app_extension".
1242 else if (Ident->getName() == "macosx_app_extension")
1243 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1244 else
1245 Platform->Ident = PP.getIdentifierInfo(
1246 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1249 // Parse the ',' following the platform name.
1250 if (ExpectAndConsume(tok::comma)) {
1251 SkipUntil(tok::r_paren, StopAtSemi);
1252 return;
1255 // If we haven't grabbed the pointers for the identifiers
1256 // "introduced", "deprecated", and "obsoleted", do so now.
1257 if (!Ident_introduced) {
1258 Ident_introduced = PP.getIdentifierInfo("introduced");
1259 Ident_deprecated = PP.getIdentifierInfo("deprecated");
1260 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1261 Ident_unavailable = PP.getIdentifierInfo("unavailable");
1262 Ident_message = PP.getIdentifierInfo("message");
1263 Ident_strict = PP.getIdentifierInfo("strict");
1264 Ident_replacement = PP.getIdentifierInfo("replacement");
1267 // Parse the optional "strict", the optional "replacement" and the set of
1268 // introductions/deprecations/removals.
1269 SourceLocation UnavailableLoc, StrictLoc;
1270 do {
1271 if (Tok.isNot(tok::identifier)) {
1272 Diag(Tok, diag::err_availability_expected_change);
1273 SkipUntil(tok::r_paren, StopAtSemi);
1274 return;
1276 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1277 SourceLocation KeywordLoc = ConsumeToken();
1279 if (Keyword == Ident_strict) {
1280 if (StrictLoc.isValid()) {
1281 Diag(KeywordLoc, diag::err_availability_redundant)
1282 << Keyword << SourceRange(StrictLoc);
1284 StrictLoc = KeywordLoc;
1285 continue;
1288 if (Keyword == Ident_unavailable) {
1289 if (UnavailableLoc.isValid()) {
1290 Diag(KeywordLoc, diag::err_availability_redundant)
1291 << Keyword << SourceRange(UnavailableLoc);
1293 UnavailableLoc = KeywordLoc;
1294 continue;
1297 if (Keyword == Ident_deprecated && Platform->Ident &&
1298 Platform->Ident->isStr("swift")) {
1299 // For swift, we deprecate for all versions.
1300 if (Changes[Deprecated].KeywordLoc.isValid()) {
1301 Diag(KeywordLoc, diag::err_availability_redundant)
1302 << Keyword
1303 << SourceRange(Changes[Deprecated].KeywordLoc);
1306 Changes[Deprecated].KeywordLoc = KeywordLoc;
1307 // Use a fake version here.
1308 Changes[Deprecated].Version = VersionTuple(1);
1309 continue;
1312 if (Tok.isNot(tok::equal)) {
1313 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1314 SkipUntil(tok::r_paren, StopAtSemi);
1315 return;
1317 ConsumeToken();
1318 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1319 if (!isTokenStringLiteral()) {
1320 Diag(Tok, diag::err_expected_string_literal)
1321 << /*Source='availability attribute'*/2;
1322 SkipUntil(tok::r_paren, StopAtSemi);
1323 return;
1325 if (Keyword == Ident_message) {
1326 MessageExpr = ParseUnevaluatedStringLiteralExpression();
1327 break;
1328 } else {
1329 ReplacementExpr = ParseUnevaluatedStringLiteralExpression();
1330 continue;
1334 // Special handling of 'NA' only when applied to introduced or
1335 // deprecated.
1336 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1337 Tok.is(tok::identifier)) {
1338 IdentifierInfo *NA = Tok.getIdentifierInfo();
1339 if (NA->getName() == "NA") {
1340 ConsumeToken();
1341 if (Keyword == Ident_introduced)
1342 UnavailableLoc = KeywordLoc;
1343 continue;
1347 SourceRange VersionRange;
1348 VersionTuple Version = ParseVersionTuple(VersionRange);
1350 if (Version.empty()) {
1351 SkipUntil(tok::r_paren, StopAtSemi);
1352 return;
1355 unsigned Index;
1356 if (Keyword == Ident_introduced)
1357 Index = Introduced;
1358 else if (Keyword == Ident_deprecated)
1359 Index = Deprecated;
1360 else if (Keyword == Ident_obsoleted)
1361 Index = Obsoleted;
1362 else
1363 Index = Unknown;
1365 if (Index < Unknown) {
1366 if (!Changes[Index].KeywordLoc.isInvalid()) {
1367 Diag(KeywordLoc, diag::err_availability_redundant)
1368 << Keyword
1369 << SourceRange(Changes[Index].KeywordLoc,
1370 Changes[Index].VersionRange.getEnd());
1373 Changes[Index].KeywordLoc = KeywordLoc;
1374 Changes[Index].Version = Version;
1375 Changes[Index].VersionRange = VersionRange;
1376 } else {
1377 Diag(KeywordLoc, diag::err_availability_unknown_change)
1378 << Keyword << VersionRange;
1381 } while (TryConsumeToken(tok::comma));
1383 // Closing ')'.
1384 if (T.consumeClose())
1385 return;
1387 if (endLoc)
1388 *endLoc = T.getCloseLocation();
1390 // The 'unavailable' availability cannot be combined with any other
1391 // availability changes. Make sure that hasn't happened.
1392 if (UnavailableLoc.isValid()) {
1393 bool Complained = false;
1394 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1395 if (Changes[Index].KeywordLoc.isValid()) {
1396 if (!Complained) {
1397 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1398 << SourceRange(Changes[Index].KeywordLoc,
1399 Changes[Index].VersionRange.getEnd());
1400 Complained = true;
1403 // Clear out the availability.
1404 Changes[Index] = AvailabilityChange();
1409 // Record this attribute
1410 attrs.addNew(&Availability,
1411 SourceRange(AvailabilityLoc, T.getCloseLocation()), ScopeName,
1412 ScopeLoc, Platform, Changes[Introduced], Changes[Deprecated],
1413 Changes[Obsoleted], UnavailableLoc, MessageExpr.get(), Form,
1414 StrictLoc, ReplacementExpr.get());
1417 /// Parse the contents of the "external_source_symbol" attribute.
1419 /// external-source-symbol-attribute:
1420 /// 'external_source_symbol' '(' keyword-arg-list ')'
1422 /// keyword-arg-list:
1423 /// keyword-arg
1424 /// keyword-arg ',' keyword-arg-list
1426 /// keyword-arg:
1427 /// 'language' '=' <string>
1428 /// 'defined_in' '=' <string>
1429 /// 'USR' '=' <string>
1430 /// 'generated_declaration'
1431 void Parser::ParseExternalSourceSymbolAttribute(
1432 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1433 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1434 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1435 // Opening '('.
1436 BalancedDelimiterTracker T(*this, tok::l_paren);
1437 if (T.expectAndConsume())
1438 return;
1440 // Initialize the pointers for the keyword identifiers when required.
1441 if (!Ident_language) {
1442 Ident_language = PP.getIdentifierInfo("language");
1443 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1444 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1445 Ident_USR = PP.getIdentifierInfo("USR");
1448 ExprResult Language;
1449 bool HasLanguage = false;
1450 ExprResult DefinedInExpr;
1451 bool HasDefinedIn = false;
1452 IdentifierLoc *GeneratedDeclaration = nullptr;
1453 ExprResult USR;
1454 bool HasUSR = false;
1456 // Parse the language/defined_in/generated_declaration keywords
1457 do {
1458 if (Tok.isNot(tok::identifier)) {
1459 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1460 SkipUntil(tok::r_paren, StopAtSemi);
1461 return;
1464 SourceLocation KeywordLoc = Tok.getLocation();
1465 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1466 if (Keyword == Ident_generated_declaration) {
1467 if (GeneratedDeclaration) {
1468 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1469 SkipUntil(tok::r_paren, StopAtSemi);
1470 return;
1472 GeneratedDeclaration = ParseIdentifierLoc();
1473 continue;
1476 if (Keyword != Ident_language && Keyword != Ident_defined_in &&
1477 Keyword != Ident_USR) {
1478 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1479 SkipUntil(tok::r_paren, StopAtSemi);
1480 return;
1483 ConsumeToken();
1484 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1485 Keyword->getName())) {
1486 SkipUntil(tok::r_paren, StopAtSemi);
1487 return;
1490 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn,
1491 HadUSR = HasUSR;
1492 if (Keyword == Ident_language)
1493 HasLanguage = true;
1494 else if (Keyword == Ident_USR)
1495 HasUSR = true;
1496 else
1497 HasDefinedIn = true;
1499 if (!isTokenStringLiteral()) {
1500 Diag(Tok, diag::err_expected_string_literal)
1501 << /*Source='external_source_symbol attribute'*/ 3
1502 << /*language | source container | USR*/ (
1503 Keyword == Ident_language
1505 : (Keyword == Ident_defined_in ? 1 : 2));
1506 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1507 continue;
1509 if (Keyword == Ident_language) {
1510 if (HadLanguage) {
1511 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1512 << Keyword;
1513 ParseUnevaluatedStringLiteralExpression();
1514 continue;
1516 Language = ParseUnevaluatedStringLiteralExpression();
1517 } else if (Keyword == Ident_USR) {
1518 if (HadUSR) {
1519 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1520 << Keyword;
1521 ParseUnevaluatedStringLiteralExpression();
1522 continue;
1524 USR = ParseUnevaluatedStringLiteralExpression();
1525 } else {
1526 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1527 if (HadDefinedIn) {
1528 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1529 << Keyword;
1530 ParseUnevaluatedStringLiteralExpression();
1531 continue;
1533 DefinedInExpr = ParseUnevaluatedStringLiteralExpression();
1535 } while (TryConsumeToken(tok::comma));
1537 // Closing ')'.
1538 if (T.consumeClose())
1539 return;
1540 if (EndLoc)
1541 *EndLoc = T.getCloseLocation();
1543 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(), GeneratedDeclaration,
1544 USR.get()};
1545 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1546 ScopeName, ScopeLoc, Args, std::size(Args), Form);
1549 /// Parse the contents of the "objc_bridge_related" attribute.
1550 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1551 /// related_class:
1552 /// Identifier
1554 /// opt-class_method:
1555 /// Identifier: | <empty>
1557 /// opt-instance_method:
1558 /// Identifier | <empty>
1560 void Parser::ParseObjCBridgeRelatedAttribute(
1561 IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc,
1562 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1563 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1564 // Opening '('.
1565 BalancedDelimiterTracker T(*this, tok::l_paren);
1566 if (T.consumeOpen()) {
1567 Diag(Tok, diag::err_expected) << tok::l_paren;
1568 return;
1571 // Parse the related class name.
1572 if (Tok.isNot(tok::identifier)) {
1573 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1574 SkipUntil(tok::r_paren, StopAtSemi);
1575 return;
1577 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1578 if (ExpectAndConsume(tok::comma)) {
1579 SkipUntil(tok::r_paren, StopAtSemi);
1580 return;
1583 // Parse class method name. It's non-optional in the sense that a trailing
1584 // comma is required, but it can be the empty string, and then we record a
1585 // nullptr.
1586 IdentifierLoc *ClassMethod = nullptr;
1587 if (Tok.is(tok::identifier)) {
1588 ClassMethod = ParseIdentifierLoc();
1589 if (!TryConsumeToken(tok::colon)) {
1590 Diag(Tok, diag::err_objcbridge_related_selector_name);
1591 SkipUntil(tok::r_paren, StopAtSemi);
1592 return;
1595 if (!TryConsumeToken(tok::comma)) {
1596 if (Tok.is(tok::colon))
1597 Diag(Tok, diag::err_objcbridge_related_selector_name);
1598 else
1599 Diag(Tok, diag::err_expected) << tok::comma;
1600 SkipUntil(tok::r_paren, StopAtSemi);
1601 return;
1604 // Parse instance method name. Also non-optional but empty string is
1605 // permitted.
1606 IdentifierLoc *InstanceMethod = nullptr;
1607 if (Tok.is(tok::identifier))
1608 InstanceMethod = ParseIdentifierLoc();
1609 else if (Tok.isNot(tok::r_paren)) {
1610 Diag(Tok, diag::err_expected) << tok::r_paren;
1611 SkipUntil(tok::r_paren, StopAtSemi);
1612 return;
1615 // Closing ')'.
1616 if (T.consumeClose())
1617 return;
1619 if (EndLoc)
1620 *EndLoc = T.getCloseLocation();
1622 // Record this attribute
1623 Attrs.addNew(&ObjCBridgeRelated,
1624 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1625 ScopeName, ScopeLoc, RelatedClass, ClassMethod, InstanceMethod,
1626 Form);
1629 void Parser::ParseSwiftNewTypeAttribute(
1630 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1631 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1632 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1633 BalancedDelimiterTracker T(*this, tok::l_paren);
1635 // Opening '('
1636 if (T.consumeOpen()) {
1637 Diag(Tok, diag::err_expected) << tok::l_paren;
1638 return;
1641 if (Tok.is(tok::r_paren)) {
1642 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1643 T.consumeClose();
1644 return;
1646 if (Tok.isNot(tok::kw_struct) && Tok.isNot(tok::kw_enum)) {
1647 Diag(Tok, diag::warn_attribute_type_not_supported)
1648 << &AttrName << Tok.getIdentifierInfo();
1649 if (!isTokenSpecial())
1650 ConsumeToken();
1651 T.consumeClose();
1652 return;
1655 auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1656 Tok.getIdentifierInfo());
1657 ConsumeToken();
1659 // Closing ')'
1660 if (T.consumeClose())
1661 return;
1662 if (EndLoc)
1663 *EndLoc = T.getCloseLocation();
1665 ArgsUnion Args[] = {SwiftType};
1666 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
1667 ScopeName, ScopeLoc, Args, std::size(Args), Form);
1670 void Parser::ParseTypeTagForDatatypeAttribute(
1671 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1672 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1673 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1674 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1676 BalancedDelimiterTracker T(*this, tok::l_paren);
1677 T.consumeOpen();
1679 if (Tok.isNot(tok::identifier)) {
1680 Diag(Tok, diag::err_expected) << tok::identifier;
1681 T.skipToEnd();
1682 return;
1684 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1686 if (ExpectAndConsume(tok::comma)) {
1687 T.skipToEnd();
1688 return;
1691 SourceRange MatchingCTypeRange;
1692 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1693 if (MatchingCType.isInvalid()) {
1694 T.skipToEnd();
1695 return;
1698 bool LayoutCompatible = false;
1699 bool MustBeNull = false;
1700 while (TryConsumeToken(tok::comma)) {
1701 if (Tok.isNot(tok::identifier)) {
1702 Diag(Tok, diag::err_expected) << tok::identifier;
1703 T.skipToEnd();
1704 return;
1706 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1707 if (Flag->isStr("layout_compatible"))
1708 LayoutCompatible = true;
1709 else if (Flag->isStr("must_be_null"))
1710 MustBeNull = true;
1711 else {
1712 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1713 T.skipToEnd();
1714 return;
1716 ConsumeToken(); // consume flag
1719 if (!T.consumeClose()) {
1720 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1721 ArgumentKind, MatchingCType.get(),
1722 LayoutCompatible, MustBeNull, Form);
1725 if (EndLoc)
1726 *EndLoc = T.getCloseLocation();
1729 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1730 /// of a C++11 attribute-specifier in a location where an attribute is not
1731 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1732 /// situation.
1734 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1735 /// this doesn't appear to actually be an attribute-specifier, and the caller
1736 /// should try to parse it.
1737 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1738 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1740 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1741 case CAK_NotAttributeSpecifier:
1742 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1743 return false;
1745 case CAK_InvalidAttributeSpecifier:
1746 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1747 return false;
1749 case CAK_AttributeSpecifier:
1750 // Parse and discard the attributes.
1751 SourceLocation BeginLoc = ConsumeBracket();
1752 ConsumeBracket();
1753 SkipUntil(tok::r_square);
1754 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1755 SourceLocation EndLoc = ConsumeBracket();
1756 Diag(BeginLoc, diag::err_attributes_not_allowed)
1757 << SourceRange(BeginLoc, EndLoc);
1758 return true;
1760 llvm_unreachable("All cases handled above.");
1763 /// We have found the opening square brackets of a C++11
1764 /// attribute-specifier in a location where an attribute is not permitted, but
1765 /// we know where the attributes ought to be written. Parse them anyway, and
1766 /// provide a fixit moving them to the right place.
1767 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
1768 SourceLocation CorrectLocation) {
1769 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1770 Tok.is(tok::kw_alignas) || Tok.isRegularKeywordAttribute());
1772 // Consume the attributes.
1773 auto Keyword =
1774 Tok.isRegularKeywordAttribute() ? Tok.getIdentifierInfo() : nullptr;
1775 SourceLocation Loc = Tok.getLocation();
1776 ParseCXX11Attributes(Attrs);
1777 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1778 // FIXME: use err_attributes_misplaced
1779 (Keyword ? Diag(Loc, diag::err_keyword_not_allowed) << Keyword
1780 : Diag(Loc, diag::err_attributes_not_allowed))
1781 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1782 << FixItHint::CreateRemoval(AttrRange);
1785 void Parser::DiagnoseProhibitedAttributes(
1786 const ParsedAttributesView &Attrs, const SourceLocation CorrectLocation) {
1787 auto *FirstAttr = Attrs.empty() ? nullptr : &Attrs.front();
1788 if (CorrectLocation.isValid()) {
1789 CharSourceRange AttrRange(Attrs.Range, true);
1790 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1791 ? Diag(CorrectLocation, diag::err_keyword_misplaced) << FirstAttr
1792 : Diag(CorrectLocation, diag::err_attributes_misplaced))
1793 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1794 << FixItHint::CreateRemoval(AttrRange);
1795 } else {
1796 const SourceRange &Range = Attrs.Range;
1797 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1798 ? Diag(Range.getBegin(), diag::err_keyword_not_allowed) << FirstAttr
1799 : Diag(Range.getBegin(), diag::err_attributes_not_allowed))
1800 << Range;
1804 void Parser::ProhibitCXX11Attributes(ParsedAttributes &Attrs,
1805 unsigned AttrDiagID,
1806 unsigned KeywordDiagID,
1807 bool DiagnoseEmptyAttrs,
1808 bool WarnOnUnknownAttrs) {
1810 if (DiagnoseEmptyAttrs && Attrs.empty() && Attrs.Range.isValid()) {
1811 // An attribute list has been parsed, but it was empty.
1812 // This is the case for [[]].
1813 const auto &LangOpts = getLangOpts();
1814 auto &SM = PP.getSourceManager();
1815 Token FirstLSquare;
1816 Lexer::getRawToken(Attrs.Range.getBegin(), FirstLSquare, SM, LangOpts);
1818 if (FirstLSquare.is(tok::l_square)) {
1819 std::optional<Token> SecondLSquare =
1820 Lexer::findNextToken(FirstLSquare.getLocation(), SM, LangOpts);
1822 if (SecondLSquare && SecondLSquare->is(tok::l_square)) {
1823 // The attribute range starts with [[, but is empty. So this must
1824 // be [[]], which we are supposed to diagnose because
1825 // DiagnoseEmptyAttrs is true.
1826 Diag(Attrs.Range.getBegin(), AttrDiagID) << Attrs.Range;
1827 return;
1832 for (const ParsedAttr &AL : Attrs) {
1833 if (AL.isRegularKeywordAttribute()) {
1834 Diag(AL.getLoc(), KeywordDiagID) << AL;
1835 AL.setInvalid();
1836 continue;
1838 if (!AL.isStandardAttributeSyntax())
1839 continue;
1840 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
1841 if (WarnOnUnknownAttrs)
1842 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1843 << AL << AL.getRange();
1844 } else {
1845 Diag(AL.getLoc(), AttrDiagID) << AL;
1846 AL.setInvalid();
1851 void Parser::DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs) {
1852 for (const ParsedAttr &PA : Attrs) {
1853 if (PA.isStandardAttributeSyntax() || PA.isRegularKeywordAttribute())
1854 Diag(PA.getLoc(), diag::ext_cxx11_attr_placement)
1855 << PA << PA.isRegularKeywordAttribute() << PA.getRange();
1859 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1860 // applies to var, not the type Foo.
1861 // As an exception to the rule, __declspec(align(...)) before the
1862 // class-key affects the type instead of the variable.
1863 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1864 // variable.
1865 // This function moves attributes that should apply to the type off DS to Attrs.
1866 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs,
1867 DeclSpec &DS,
1868 Sema::TagUseKind TUK) {
1869 if (TUK == Sema::TUK_Reference)
1870 return;
1872 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
1874 for (ParsedAttr &AL : DS.getAttributes()) {
1875 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1876 AL.isDeclspecAttribute()) ||
1877 AL.isMicrosoftAttribute())
1878 ToBeMoved.push_back(&AL);
1881 for (ParsedAttr *AL : ToBeMoved) {
1882 DS.getAttributes().remove(AL);
1883 Attrs.addAtEnd(AL);
1887 /// ParseDeclaration - Parse a full 'declaration', which consists of
1888 /// declaration-specifiers, some number of declarators, and a semicolon.
1889 /// 'Context' should be a DeclaratorContext value. This returns the
1890 /// location of the semicolon in DeclEnd.
1892 /// declaration: [C99 6.7]
1893 /// block-declaration ->
1894 /// simple-declaration
1895 /// others [FIXME]
1896 /// [C++] template-declaration
1897 /// [C++] namespace-definition
1898 /// [C++] using-directive
1899 /// [C++] using-declaration
1900 /// [C++11/C11] static_assert-declaration
1901 /// others... [FIXME]
1903 Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
1904 SourceLocation &DeclEnd,
1905 ParsedAttributes &DeclAttrs,
1906 ParsedAttributes &DeclSpecAttrs,
1907 SourceLocation *DeclSpecStart) {
1908 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1909 // Must temporarily exit the objective-c container scope for
1910 // parsing c none objective-c decls.
1911 ObjCDeclContextSwitch ObjCDC(*this);
1913 Decl *SingleDecl = nullptr;
1914 switch (Tok.getKind()) {
1915 case tok::kw_template:
1916 case tok::kw_export:
1917 ProhibitAttributes(DeclAttrs);
1918 ProhibitAttributes(DeclSpecAttrs);
1919 SingleDecl =
1920 ParseDeclarationStartingWithTemplate(Context, DeclEnd, DeclAttrs);
1921 break;
1922 case tok::kw_inline:
1923 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1924 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1925 ProhibitAttributes(DeclAttrs);
1926 ProhibitAttributes(DeclSpecAttrs);
1927 SourceLocation InlineLoc = ConsumeToken();
1928 return ParseNamespace(Context, DeclEnd, InlineLoc);
1930 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1931 true, nullptr, DeclSpecStart);
1933 case tok::kw_cbuffer:
1934 case tok::kw_tbuffer:
1935 SingleDecl = ParseHLSLBuffer(DeclEnd);
1936 break;
1937 case tok::kw_namespace:
1938 ProhibitAttributes(DeclAttrs);
1939 ProhibitAttributes(DeclSpecAttrs);
1940 return ParseNamespace(Context, DeclEnd);
1941 case tok::kw_using: {
1942 ParsedAttributes Attrs(AttrFactory);
1943 takeAndConcatenateAttrs(DeclAttrs, DeclSpecAttrs, Attrs);
1944 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1945 DeclEnd, Attrs);
1947 case tok::kw_static_assert:
1948 case tok::kw__Static_assert:
1949 ProhibitAttributes(DeclAttrs);
1950 ProhibitAttributes(DeclSpecAttrs);
1951 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1952 break;
1953 default:
1954 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1955 true, nullptr, DeclSpecStart);
1958 // This routine returns a DeclGroup, if the thing we parsed only contains a
1959 // single decl, convert it now.
1960 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1963 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1964 /// declaration-specifiers init-declarator-list[opt] ';'
1965 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1966 /// init-declarator-list ';'
1967 ///[C90/C++]init-declarator-list ';' [TODO]
1968 /// [OMP] threadprivate-directive
1969 /// [OMP] allocate-directive [TODO]
1971 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1972 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1974 /// If RequireSemi is false, this does not check for a ';' at the end of the
1975 /// declaration. If it is true, it checks for and eats it.
1977 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1978 /// of a simple-declaration. If we find that we are, we also parse the
1979 /// for-range-initializer, and place it here.
1981 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1982 /// the Declaration. The SourceLocation for this Decl is set to
1983 /// DeclSpecStart if DeclSpecStart is non-null.
1984 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1985 DeclaratorContext Context, SourceLocation &DeclEnd,
1986 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
1987 bool RequireSemi, ForRangeInit *FRI, SourceLocation *DeclSpecStart) {
1988 // Need to retain these for diagnostics before we add them to the DeclSepc.
1989 ParsedAttributesView OriginalDeclSpecAttrs;
1990 OriginalDeclSpecAttrs.addAll(DeclSpecAttrs.begin(), DeclSpecAttrs.end());
1991 OriginalDeclSpecAttrs.Range = DeclSpecAttrs.Range;
1993 // Parse the common declaration-specifiers piece.
1994 ParsingDeclSpec DS(*this);
1995 DS.takeAttributesFrom(DeclSpecAttrs);
1997 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1998 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
2000 // If we had a free-standing type definition with a missing semicolon, we
2001 // may get this far before the problem becomes obvious.
2002 if (DS.hasTagDefinition() &&
2003 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
2004 return nullptr;
2006 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
2007 // declaration-specifiers init-declarator-list[opt] ';'
2008 if (Tok.is(tok::semi)) {
2009 ProhibitAttributes(DeclAttrs);
2010 DeclEnd = Tok.getLocation();
2011 if (RequireSemi) ConsumeToken();
2012 RecordDecl *AnonRecord = nullptr;
2013 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2014 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
2015 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
2016 DS.complete(TheDecl);
2017 if (AnonRecord) {
2018 Decl* decls[] = {AnonRecord, TheDecl};
2019 return Actions.BuildDeclaratorGroup(decls);
2021 return Actions.ConvertDeclToDeclGroup(TheDecl);
2024 if (DS.hasTagDefinition())
2025 Actions.ActOnDefinedDeclarationSpecifier(DS.getRepAsDecl());
2027 if (DeclSpecStart)
2028 DS.SetRangeStart(*DeclSpecStart);
2030 return ParseDeclGroup(DS, Context, DeclAttrs, &DeclEnd, FRI);
2033 /// Returns true if this might be the start of a declarator, or a common typo
2034 /// for a declarator.
2035 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
2036 switch (Tok.getKind()) {
2037 case tok::annot_cxxscope:
2038 case tok::annot_template_id:
2039 case tok::caret:
2040 case tok::code_completion:
2041 case tok::coloncolon:
2042 case tok::ellipsis:
2043 case tok::kw___attribute:
2044 case tok::kw_operator:
2045 case tok::l_paren:
2046 case tok::star:
2047 return true;
2049 case tok::amp:
2050 case tok::ampamp:
2051 return getLangOpts().CPlusPlus;
2053 case tok::l_square: // Might be an attribute on an unnamed bit-field.
2054 return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
2055 NextToken().is(tok::l_square);
2057 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
2058 return Context == DeclaratorContext::Member || getLangOpts().CPlusPlus;
2060 case tok::identifier:
2061 switch (NextToken().getKind()) {
2062 case tok::code_completion:
2063 case tok::coloncolon:
2064 case tok::comma:
2065 case tok::equal:
2066 case tok::equalequal: // Might be a typo for '='.
2067 case tok::kw_alignas:
2068 case tok::kw_asm:
2069 case tok::kw___attribute:
2070 case tok::l_brace:
2071 case tok::l_paren:
2072 case tok::l_square:
2073 case tok::less:
2074 case tok::r_brace:
2075 case tok::r_paren:
2076 case tok::r_square:
2077 case tok::semi:
2078 return true;
2080 case tok::colon:
2081 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
2082 // and in block scope it's probably a label. Inside a class definition,
2083 // this is a bit-field.
2084 return Context == DeclaratorContext::Member ||
2085 (getLangOpts().CPlusPlus && Context == DeclaratorContext::File);
2087 case tok::identifier: // Possible virt-specifier.
2088 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
2090 default:
2091 return Tok.isRegularKeywordAttribute();
2094 default:
2095 return Tok.isRegularKeywordAttribute();
2099 /// Skip until we reach something which seems like a sensible place to pick
2100 /// up parsing after a malformed declaration. This will sometimes stop sooner
2101 /// than SkipUntil(tok::r_brace) would, but will never stop later.
2102 void Parser::SkipMalformedDecl() {
2103 while (true) {
2104 switch (Tok.getKind()) {
2105 case tok::l_brace:
2106 // Skip until matching }, then stop. We've probably skipped over
2107 // a malformed class or function definition or similar.
2108 ConsumeBrace();
2109 SkipUntil(tok::r_brace);
2110 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
2111 // This declaration isn't over yet. Keep skipping.
2112 continue;
2114 TryConsumeToken(tok::semi);
2115 return;
2117 case tok::l_square:
2118 ConsumeBracket();
2119 SkipUntil(tok::r_square);
2120 continue;
2122 case tok::l_paren:
2123 ConsumeParen();
2124 SkipUntil(tok::r_paren);
2125 continue;
2127 case tok::r_brace:
2128 return;
2130 case tok::semi:
2131 ConsumeToken();
2132 return;
2134 case tok::kw_inline:
2135 // 'inline namespace' at the start of a line is almost certainly
2136 // a good place to pick back up parsing, except in an Objective-C
2137 // @interface context.
2138 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
2139 (!ParsingInObjCContainer || CurParsedObjCImpl))
2140 return;
2141 break;
2143 case tok::kw_namespace:
2144 // 'namespace' at the start of a line is almost certainly a good
2145 // place to pick back up parsing, except in an Objective-C
2146 // @interface context.
2147 if (Tok.isAtStartOfLine() &&
2148 (!ParsingInObjCContainer || CurParsedObjCImpl))
2149 return;
2150 break;
2152 case tok::at:
2153 // @end is very much like } in Objective-C contexts.
2154 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
2155 ParsingInObjCContainer)
2156 return;
2157 break;
2159 case tok::minus:
2160 case tok::plus:
2161 // - and + probably start new method declarations in Objective-C contexts.
2162 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
2163 return;
2164 break;
2166 case tok::eof:
2167 case tok::annot_module_begin:
2168 case tok::annot_module_end:
2169 case tok::annot_module_include:
2170 case tok::annot_repl_input_end:
2171 return;
2173 default:
2174 break;
2177 ConsumeAnyToken();
2181 /// ParseDeclGroup - Having concluded that this is either a function
2182 /// definition or a group of object declarations, actually parse the
2183 /// result.
2184 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2185 DeclaratorContext Context,
2186 ParsedAttributes &Attrs,
2187 SourceLocation *DeclEnd,
2188 ForRangeInit *FRI) {
2189 // Parse the first declarator.
2190 // Consume all of the attributes from `Attrs` by moving them to our own local
2191 // list. This ensures that we will not attempt to interpret them as statement
2192 // attributes higher up the callchain.
2193 ParsedAttributes LocalAttrs(AttrFactory);
2194 LocalAttrs.takeAllFrom(Attrs);
2195 ParsingDeclarator D(*this, DS, LocalAttrs, Context);
2196 ParseDeclarator(D);
2198 // Bail out if the first declarator didn't seem well-formed.
2199 if (!D.hasName() && !D.mayOmitIdentifier()) {
2200 SkipMalformedDecl();
2201 return nullptr;
2204 if (getLangOpts().HLSL)
2205 MaybeParseHLSLSemantics(D);
2207 if (Tok.is(tok::kw_requires))
2208 ParseTrailingRequiresClause(D);
2210 // Save late-parsed attributes for now; they need to be parsed in the
2211 // appropriate function scope after the function Decl has been constructed.
2212 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2213 LateParsedAttrList LateParsedAttrs(true);
2214 if (D.isFunctionDeclarator()) {
2215 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2217 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2218 // attribute. If we find the keyword here, tell the user to put it
2219 // at the start instead.
2220 if (Tok.is(tok::kw__Noreturn)) {
2221 SourceLocation Loc = ConsumeToken();
2222 const char *PrevSpec;
2223 unsigned DiagID;
2225 // We can offer a fixit if it's valid to mark this function as _Noreturn
2226 // and we don't have any other declarators in this declaration.
2227 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2228 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2229 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2231 Diag(Loc, diag::err_c11_noreturn_misplaced)
2232 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2233 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2234 : FixItHint());
2237 // Check to see if we have a function *definition* which must have a body.
2238 if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
2239 cutOffParsing();
2240 Actions.CodeCompleteAfterFunctionEquals(D);
2241 return nullptr;
2243 // We're at the point where the parsing of function declarator is finished.
2245 // A common error is that users accidently add a virtual specifier
2246 // (e.g. override) in an out-line method definition.
2247 // We attempt to recover by stripping all these specifiers coming after
2248 // the declarator.
2249 while (auto Specifier = isCXX11VirtSpecifier()) {
2250 Diag(Tok, diag::err_virt_specifier_outside_class)
2251 << VirtSpecifiers::getSpecifierName(Specifier)
2252 << FixItHint::CreateRemoval(Tok.getLocation());
2253 ConsumeToken();
2255 // Look at the next token to make sure that this isn't a function
2256 // declaration. We have to check this because __attribute__ might be the
2257 // start of a function definition in GCC-extended K&R C.
2258 if (!isDeclarationAfterDeclarator()) {
2260 // Function definitions are only allowed at file scope and in C++ classes.
2261 // The C++ inline method definition case is handled elsewhere, so we only
2262 // need to handle the file scope definition case.
2263 if (Context == DeclaratorContext::File) {
2264 if (isStartOfFunctionDefinition(D)) {
2265 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2266 Diag(Tok, diag::err_function_declared_typedef);
2268 // Recover by treating the 'typedef' as spurious.
2269 DS.ClearStorageClassSpecs();
2272 Decl *TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
2273 &LateParsedAttrs);
2274 return Actions.ConvertDeclToDeclGroup(TheDecl);
2277 if (isDeclarationSpecifier(ImplicitTypenameContext::No) ||
2278 Tok.is(tok::kw_namespace)) {
2279 // If there is an invalid declaration specifier or a namespace
2280 // definition right after the function prototype, then we must be in a
2281 // missing semicolon case where this isn't actually a body. Just fall
2282 // through into the code that handles it as a prototype, and let the
2283 // top-level code handle the erroneous declspec where it would
2284 // otherwise expect a comma or semicolon. Note that
2285 // isDeclarationSpecifier already covers 'inline namespace', since
2286 // 'inline' can be a declaration specifier.
2287 } else {
2288 Diag(Tok, diag::err_expected_fn_body);
2289 SkipUntil(tok::semi);
2290 return nullptr;
2292 } else {
2293 if (Tok.is(tok::l_brace)) {
2294 Diag(Tok, diag::err_function_definition_not_allowed);
2295 SkipMalformedDecl();
2296 return nullptr;
2302 if (ParseAsmAttributesAfterDeclarator(D))
2303 return nullptr;
2305 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2306 // must parse and analyze the for-range-initializer before the declaration is
2307 // analyzed.
2309 // Handle the Objective-C for-in loop variable similarly, although we
2310 // don't need to parse the container in advance.
2311 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2312 bool IsForRangeLoop = false;
2313 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2314 IsForRangeLoop = true;
2315 if (getLangOpts().OpenMP)
2316 Actions.startOpenMPCXXRangeFor();
2317 if (Tok.is(tok::l_brace))
2318 FRI->RangeExpr = ParseBraceInitializer();
2319 else
2320 FRI->RangeExpr = ParseExpression();
2323 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2324 if (IsForRangeLoop) {
2325 Actions.ActOnCXXForRangeDecl(ThisDecl);
2326 } else {
2327 // Obj-C for loop
2328 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2329 VD->setObjCForDecl(true);
2331 Actions.FinalizeDeclaration(ThisDecl);
2332 D.complete(ThisDecl);
2333 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2336 SmallVector<Decl *, 8> DeclsInGroup;
2337 Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2338 D, ParsedTemplateInfo(), FRI);
2339 if (LateParsedAttrs.size() > 0)
2340 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2341 D.complete(FirstDecl);
2342 if (FirstDecl)
2343 DeclsInGroup.push_back(FirstDecl);
2345 bool ExpectSemi = Context != DeclaratorContext::ForInit;
2347 // If we don't have a comma, it is either the end of the list (a ';') or an
2348 // error, bail out.
2349 SourceLocation CommaLoc;
2350 while (TryConsumeToken(tok::comma, CommaLoc)) {
2351 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2352 // This comma was followed by a line-break and something which can't be
2353 // the start of a declarator. The comma was probably a typo for a
2354 // semicolon.
2355 Diag(CommaLoc, diag::err_expected_semi_declaration)
2356 << FixItHint::CreateReplacement(CommaLoc, ";");
2357 ExpectSemi = false;
2358 break;
2361 // Parse the next declarator.
2362 D.clear();
2363 D.setCommaLoc(CommaLoc);
2365 // Accept attributes in an init-declarator. In the first declarator in a
2366 // declaration, these would be part of the declspec. In subsequent
2367 // declarators, they become part of the declarator itself, so that they
2368 // don't apply to declarators after *this* one. Examples:
2369 // short __attribute__((common)) var; -> declspec
2370 // short var __attribute__((common)); -> declarator
2371 // short x, __attribute__((common)) var; -> declarator
2372 MaybeParseGNUAttributes(D);
2374 // MSVC parses but ignores qualifiers after the comma as an extension.
2375 if (getLangOpts().MicrosoftExt)
2376 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2378 ParseDeclarator(D);
2380 if (getLangOpts().HLSL)
2381 MaybeParseHLSLSemantics(D);
2383 if (!D.isInvalidType()) {
2384 // C++2a [dcl.decl]p1
2385 // init-declarator:
2386 // declarator initializer[opt]
2387 // declarator requires-clause
2388 if (Tok.is(tok::kw_requires))
2389 ParseTrailingRequiresClause(D);
2390 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2391 D.complete(ThisDecl);
2392 if (ThisDecl)
2393 DeclsInGroup.push_back(ThisDecl);
2397 if (DeclEnd)
2398 *DeclEnd = Tok.getLocation();
2400 if (ExpectSemi && ExpectAndConsumeSemi(
2401 Context == DeclaratorContext::File
2402 ? diag::err_invalid_token_after_toplevel_declarator
2403 : diag::err_expected_semi_declaration)) {
2404 // Okay, there was no semicolon and one was expected. If we see a
2405 // declaration specifier, just assume it was missing and continue parsing.
2406 // Otherwise things are very confused and we skip to recover.
2407 if (!isDeclarationSpecifier(ImplicitTypenameContext::No))
2408 SkipMalformedDecl();
2411 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2414 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2415 /// declarator. Returns true on an error.
2416 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2417 // If a simple-asm-expr is present, parse it.
2418 if (Tok.is(tok::kw_asm)) {
2419 SourceLocation Loc;
2420 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2421 if (AsmLabel.isInvalid()) {
2422 SkipUntil(tok::semi, StopBeforeMatch);
2423 return true;
2426 D.setAsmLabel(AsmLabel.get());
2427 D.SetRangeEnd(Loc);
2430 MaybeParseGNUAttributes(D);
2431 return false;
2434 /// Parse 'declaration' after parsing 'declaration-specifiers
2435 /// declarator'. This method parses the remainder of the declaration
2436 /// (including any attributes or initializer, among other things) and
2437 /// finalizes the declaration.
2439 /// init-declarator: [C99 6.7]
2440 /// declarator
2441 /// declarator '=' initializer
2442 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2443 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2444 /// [C++] declarator initializer[opt]
2446 /// [C++] initializer:
2447 /// [C++] '=' initializer-clause
2448 /// [C++] '(' expression-list ')'
2449 /// [C++0x] '=' 'default' [TODO]
2450 /// [C++0x] '=' 'delete'
2451 /// [C++0x] braced-init-list
2453 /// According to the standard grammar, =default and =delete are function
2454 /// definitions, but that definitely doesn't fit with the parser here.
2456 Decl *Parser::ParseDeclarationAfterDeclarator(
2457 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2458 if (ParseAsmAttributesAfterDeclarator(D))
2459 return nullptr;
2461 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2464 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2465 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2466 // RAII type used to track whether we're inside an initializer.
2467 struct InitializerScopeRAII {
2468 Parser &P;
2469 Declarator &D;
2470 Decl *ThisDecl;
2472 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2473 : P(P), D(D), ThisDecl(ThisDecl) {
2474 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2475 Scope *S = nullptr;
2476 if (D.getCXXScopeSpec().isSet()) {
2477 P.EnterScope(0);
2478 S = P.getCurScope();
2480 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2483 ~InitializerScopeRAII() { pop(); }
2484 void pop() {
2485 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2486 Scope *S = nullptr;
2487 if (D.getCXXScopeSpec().isSet())
2488 S = P.getCurScope();
2489 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2490 if (S)
2491 P.ExitScope();
2493 ThisDecl = nullptr;
2497 enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
2498 InitKind TheInitKind;
2499 // If a '==' or '+=' is found, suggest a fixit to '='.
2500 if (isTokenEqualOrEqualTypo())
2501 TheInitKind = InitKind::Equal;
2502 else if (Tok.is(tok::l_paren))
2503 TheInitKind = InitKind::CXXDirect;
2504 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2505 (!CurParsedObjCImpl || !D.isFunctionDeclarator()))
2506 TheInitKind = InitKind::CXXBraced;
2507 else
2508 TheInitKind = InitKind::Uninitialized;
2509 if (TheInitKind != InitKind::Uninitialized)
2510 D.setHasInitializer();
2512 // Inform Sema that we just parsed this declarator.
2513 Decl *ThisDecl = nullptr;
2514 Decl *OuterDecl = nullptr;
2515 switch (TemplateInfo.Kind) {
2516 case ParsedTemplateInfo::NonTemplate:
2517 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2518 break;
2520 case ParsedTemplateInfo::Template:
2521 case ParsedTemplateInfo::ExplicitSpecialization: {
2522 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2523 *TemplateInfo.TemplateParams,
2525 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2526 // Re-direct this decl to refer to the templated decl so that we can
2527 // initialize it.
2528 ThisDecl = VT->getTemplatedDecl();
2529 OuterDecl = VT;
2531 break;
2533 case ParsedTemplateInfo::ExplicitInstantiation: {
2534 if (Tok.is(tok::semi)) {
2535 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2536 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2537 if (ThisRes.isInvalid()) {
2538 SkipUntil(tok::semi, StopBeforeMatch);
2539 return nullptr;
2541 ThisDecl = ThisRes.get();
2542 } else {
2543 // FIXME: This check should be for a variable template instantiation only.
2545 // Check that this is a valid instantiation
2546 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2547 // If the declarator-id is not a template-id, issue a diagnostic and
2548 // recover by ignoring the 'template' keyword.
2549 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2550 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2551 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2552 } else {
2553 SourceLocation LAngleLoc =
2554 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2555 Diag(D.getIdentifierLoc(),
2556 diag::err_explicit_instantiation_with_definition)
2557 << SourceRange(TemplateInfo.TemplateLoc)
2558 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2560 // Recover as if it were an explicit specialization.
2561 TemplateParameterLists FakedParamLists;
2562 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2563 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc,
2564 std::nullopt, LAngleLoc, nullptr));
2566 ThisDecl =
2567 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2570 break;
2574 Sema::CUDATargetContextRAII X(Actions, Sema::CTCK_InitGlobalVar, ThisDecl);
2575 switch (TheInitKind) {
2576 // Parse declarator '=' initializer.
2577 case InitKind::Equal: {
2578 SourceLocation EqualLoc = ConsumeToken();
2580 if (Tok.is(tok::kw_delete)) {
2581 if (D.isFunctionDeclarator())
2582 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2583 << 1 /* delete */;
2584 else
2585 Diag(ConsumeToken(), diag::err_deleted_non_function);
2586 } else if (Tok.is(tok::kw_default)) {
2587 if (D.isFunctionDeclarator())
2588 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2589 << 0 /* default */;
2590 else
2591 Diag(ConsumeToken(), diag::err_default_special_members)
2592 << getLangOpts().CPlusPlus20;
2593 } else {
2594 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2596 if (Tok.is(tok::code_completion)) {
2597 cutOffParsing();
2598 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2599 Actions.FinalizeDeclaration(ThisDecl);
2600 return nullptr;
2603 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2604 ExprResult Init = ParseInitializer();
2606 // If this is the only decl in (possibly) range based for statement,
2607 // our best guess is that the user meant ':' instead of '='.
2608 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2609 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2610 << FixItHint::CreateReplacement(EqualLoc, ":");
2611 // We are trying to stop parser from looking for ';' in this for
2612 // statement, therefore preventing spurious errors to be issued.
2613 FRI->ColonLoc = EqualLoc;
2614 Init = ExprError();
2615 FRI->RangeExpr = Init;
2618 InitScope.pop();
2620 if (Init.isInvalid()) {
2621 SmallVector<tok::TokenKind, 2> StopTokens;
2622 StopTokens.push_back(tok::comma);
2623 if (D.getContext() == DeclaratorContext::ForInit ||
2624 D.getContext() == DeclaratorContext::SelectionInit)
2625 StopTokens.push_back(tok::r_paren);
2626 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2627 Actions.ActOnInitializerError(ThisDecl);
2628 } else
2629 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2630 /*DirectInit=*/false);
2632 break;
2634 case InitKind::CXXDirect: {
2635 // Parse C++ direct initializer: '(' expression-list ')'
2636 BalancedDelimiterTracker T(*this, tok::l_paren);
2637 T.consumeOpen();
2639 ExprVector Exprs;
2641 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2643 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2644 auto RunSignatureHelp = [&]() {
2645 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2646 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2647 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2648 /*Braced=*/false);
2649 CalledSignatureHelp = true;
2650 return PreferredType;
2652 auto SetPreferredType = [&] {
2653 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2656 llvm::function_ref<void()> ExpressionStarts;
2657 if (ThisVarDecl) {
2658 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2659 // VarDecl. This is an error and it is reported in a call to
2660 // Actions.ActOnInitializerError(). However, we call
2661 // ProduceConstructorSignatureHelp only on VarDecls.
2662 ExpressionStarts = SetPreferredType;
2664 if (ParseExpressionList(Exprs, ExpressionStarts)) {
2665 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2666 Actions.ProduceConstructorSignatureHelp(
2667 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2668 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2669 /*Braced=*/false);
2670 CalledSignatureHelp = true;
2672 Actions.ActOnInitializerError(ThisDecl);
2673 SkipUntil(tok::r_paren, StopAtSemi);
2674 } else {
2675 // Match the ')'.
2676 T.consumeClose();
2677 InitScope.pop();
2679 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2680 T.getCloseLocation(),
2681 Exprs);
2682 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2683 /*DirectInit=*/true);
2685 break;
2687 case InitKind::CXXBraced: {
2688 // Parse C++0x braced-init-list.
2689 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2691 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2693 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2694 ExprResult Init(ParseBraceInitializer());
2696 InitScope.pop();
2698 if (Init.isInvalid()) {
2699 Actions.ActOnInitializerError(ThisDecl);
2700 } else
2701 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2702 break;
2704 case InitKind::Uninitialized: {
2705 Actions.ActOnUninitializedDecl(ThisDecl);
2706 break;
2710 Actions.FinalizeDeclaration(ThisDecl);
2711 return OuterDecl ? OuterDecl : ThisDecl;
2714 /// ParseSpecifierQualifierList
2715 /// specifier-qualifier-list:
2716 /// type-specifier specifier-qualifier-list[opt]
2717 /// type-qualifier specifier-qualifier-list[opt]
2718 /// [GNU] attributes specifier-qualifier-list[opt]
2720 void Parser::ParseSpecifierQualifierList(
2721 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2722 AccessSpecifier AS, DeclSpecContext DSC) {
2723 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2724 /// parse declaration-specifiers and complain about extra stuff.
2725 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2726 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC, nullptr,
2727 AllowImplicitTypename);
2729 // Validate declspec for type-name.
2730 unsigned Specs = DS.getParsedSpecifiers();
2731 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2732 Diag(Tok, diag::err_expected_type);
2733 DS.SetTypeSpecError();
2734 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2735 Diag(Tok, diag::err_typename_requires_specqual);
2736 if (!DS.hasTypeSpecifier())
2737 DS.SetTypeSpecError();
2740 // Issue diagnostic and remove storage class if present.
2741 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2742 if (DS.getStorageClassSpecLoc().isValid())
2743 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2744 else
2745 Diag(DS.getThreadStorageClassSpecLoc(),
2746 diag::err_typename_invalid_storageclass);
2747 DS.ClearStorageClassSpecs();
2750 // Issue diagnostic and remove function specifier if present.
2751 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2752 if (DS.isInlineSpecified())
2753 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2754 if (DS.isVirtualSpecified())
2755 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2756 if (DS.hasExplicitSpecifier())
2757 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2758 if (DS.isNoreturnSpecified())
2759 Diag(DS.getNoreturnSpecLoc(), diag::err_typename_invalid_functionspec);
2760 DS.ClearFunctionSpecs();
2763 // Issue diagnostic and remove constexpr specifier if present.
2764 if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2765 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2766 << static_cast<int>(DS.getConstexprSpecifier());
2767 DS.ClearConstexprSpec();
2771 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2772 /// specified token is valid after the identifier in a declarator which
2773 /// immediately follows the declspec. For example, these things are valid:
2775 /// int x [ 4]; // direct-declarator
2776 /// int x ( int y); // direct-declarator
2777 /// int(int x ) // direct-declarator
2778 /// int x ; // simple-declaration
2779 /// int x = 17; // init-declarator-list
2780 /// int x , y; // init-declarator-list
2781 /// int x __asm__ ("foo"); // init-declarator-list
2782 /// int x : 4; // struct-declarator
2783 /// int x { 5}; // C++'0x unified initializers
2785 /// This is not, because 'x' does not immediately follow the declspec (though
2786 /// ')' happens to be valid anyway).
2787 /// int (x)
2789 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2790 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2791 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2792 tok::colon);
2795 /// ParseImplicitInt - This method is called when we have an non-typename
2796 /// identifier in a declspec (which normally terminates the decl spec) when
2797 /// the declspec has no type specifier. In this case, the declspec is either
2798 /// malformed or is "implicit int" (in K&R and C89).
2800 /// This method handles diagnosing this prettily and returns false if the
2801 /// declspec is done being processed. If it recovers and thinks there may be
2802 /// other pieces of declspec after it, it returns true.
2804 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2805 const ParsedTemplateInfo &TemplateInfo,
2806 AccessSpecifier AS, DeclSpecContext DSC,
2807 ParsedAttributes &Attrs) {
2808 assert(Tok.is(tok::identifier) && "should have identifier");
2810 SourceLocation Loc = Tok.getLocation();
2811 // If we see an identifier that is not a type name, we normally would
2812 // parse it as the identifier being declared. However, when a typename
2813 // is typo'd or the definition is not included, this will incorrectly
2814 // parse the typename as the identifier name and fall over misparsing
2815 // later parts of the diagnostic.
2817 // As such, we try to do some look-ahead in cases where this would
2818 // otherwise be an "implicit-int" case to see if this is invalid. For
2819 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2820 // an identifier with implicit int, we'd get a parse error because the
2821 // next token is obviously invalid for a type. Parse these as a case
2822 // with an invalid type specifier.
2823 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2825 // Since we know that this either implicit int (which is rare) or an
2826 // error, do lookahead to try to do better recovery. This never applies
2827 // within a type specifier. Outside of C++, we allow this even if the
2828 // language doesn't "officially" support implicit int -- we support
2829 // implicit int as an extension in some language modes.
2830 if (!isTypeSpecifier(DSC) && getLangOpts().isImplicitIntAllowed() &&
2831 isValidAfterIdentifierInDeclarator(NextToken())) {
2832 // If this token is valid for implicit int, e.g. "static x = 4", then
2833 // we just avoid eating the identifier, so it will be parsed as the
2834 // identifier in the declarator.
2835 return false;
2838 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2839 // for incomplete declarations such as `pipe p`.
2840 if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2841 return false;
2843 if (getLangOpts().CPlusPlus &&
2844 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2845 // Don't require a type specifier if we have the 'auto' storage class
2846 // specifier in C++98 -- we'll promote it to a type specifier.
2847 if (SS)
2848 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2849 return false;
2852 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2853 getLangOpts().MSVCCompat) {
2854 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2855 // Give Sema a chance to recover if we are in a template with dependent base
2856 // classes.
2857 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2858 *Tok.getIdentifierInfo(), Tok.getLocation(),
2859 DSC == DeclSpecContext::DSC_template_type_arg)) {
2860 const char *PrevSpec;
2861 unsigned DiagID;
2862 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2863 Actions.getASTContext().getPrintingPolicy());
2864 DS.SetRangeEnd(Tok.getLocation());
2865 ConsumeToken();
2866 return false;
2870 // Otherwise, if we don't consume this token, we are going to emit an
2871 // error anyway. Try to recover from various common problems. Check
2872 // to see if this was a reference to a tag name without a tag specified.
2873 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2875 // C++ doesn't need this, and isTagName doesn't take SS.
2876 if (SS == nullptr) {
2877 const char *TagName = nullptr, *FixitTagName = nullptr;
2878 tok::TokenKind TagKind = tok::unknown;
2880 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2881 default: break;
2882 case DeclSpec::TST_enum:
2883 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2884 case DeclSpec::TST_union:
2885 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2886 case DeclSpec::TST_struct:
2887 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2888 case DeclSpec::TST_interface:
2889 TagName="__interface"; FixitTagName = "__interface ";
2890 TagKind=tok::kw___interface;break;
2891 case DeclSpec::TST_class:
2892 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2895 if (TagName) {
2896 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2897 LookupResult R(Actions, TokenName, SourceLocation(),
2898 Sema::LookupOrdinaryName);
2900 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2901 << TokenName << TagName << getLangOpts().CPlusPlus
2902 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2904 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2905 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2906 I != IEnd; ++I)
2907 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2908 << TokenName << TagName;
2911 // Parse this as a tag as if the missing tag were present.
2912 if (TagKind == tok::kw_enum)
2913 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2914 DeclSpecContext::DSC_normal);
2915 else
2916 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2917 /*EnteringContext*/ false,
2918 DeclSpecContext::DSC_normal, Attrs);
2919 return true;
2923 // Determine whether this identifier could plausibly be the name of something
2924 // being declared (with a missing type).
2925 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2926 DSC == DeclSpecContext::DSC_class)) {
2927 // Look ahead to the next token to try to figure out what this declaration
2928 // was supposed to be.
2929 switch (NextToken().getKind()) {
2930 case tok::l_paren: {
2931 // static x(4); // 'x' is not a type
2932 // x(int n); // 'x' is not a type
2933 // x (*p)[]; // 'x' is a type
2935 // Since we're in an error case, we can afford to perform a tentative
2936 // parse to determine which case we're in.
2937 TentativeParsingAction PA(*this);
2938 ConsumeToken();
2939 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2940 PA.Revert();
2942 if (TPR != TPResult::False) {
2943 // The identifier is followed by a parenthesized declarator.
2944 // It's supposed to be a type.
2945 break;
2948 // If we're in a context where we could be declaring a constructor,
2949 // check whether this is a constructor declaration with a bogus name.
2950 if (DSC == DeclSpecContext::DSC_class ||
2951 (DSC == DeclSpecContext::DSC_top_level && SS)) {
2952 IdentifierInfo *II = Tok.getIdentifierInfo();
2953 if (Actions.isCurrentClassNameTypo(II, SS)) {
2954 Diag(Loc, diag::err_constructor_bad_name)
2955 << Tok.getIdentifierInfo() << II
2956 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2957 Tok.setIdentifierInfo(II);
2960 // Fall through.
2961 [[fallthrough]];
2963 case tok::comma:
2964 case tok::equal:
2965 case tok::kw_asm:
2966 case tok::l_brace:
2967 case tok::l_square:
2968 case tok::semi:
2969 // This looks like a variable or function declaration. The type is
2970 // probably missing. We're done parsing decl-specifiers.
2971 // But only if we are not in a function prototype scope.
2972 if (getCurScope()->isFunctionPrototypeScope())
2973 break;
2974 if (SS)
2975 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2976 return false;
2978 default:
2979 // This is probably supposed to be a type. This includes cases like:
2980 // int f(itn);
2981 // struct S { unsigned : 4; };
2982 break;
2986 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2987 // and attempt to recover.
2988 ParsedType T;
2989 IdentifierInfo *II = Tok.getIdentifierInfo();
2990 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2991 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2992 IsTemplateName);
2993 if (T) {
2994 // The action has suggested that the type T could be used. Set that as
2995 // the type in the declaration specifiers, consume the would-be type
2996 // name token, and we're done.
2997 const char *PrevSpec;
2998 unsigned DiagID;
2999 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
3000 Actions.getASTContext().getPrintingPolicy());
3001 DS.SetRangeEnd(Tok.getLocation());
3002 ConsumeToken();
3003 // There may be other declaration specifiers after this.
3004 return true;
3005 } else if (II != Tok.getIdentifierInfo()) {
3006 // If no type was suggested, the correction is to a keyword
3007 Tok.setKind(II->getTokenID());
3008 // There may be other declaration specifiers after this.
3009 return true;
3012 // Otherwise, the action had no suggestion for us. Mark this as an error.
3013 DS.SetTypeSpecError();
3014 DS.SetRangeEnd(Tok.getLocation());
3015 ConsumeToken();
3017 // Eat any following template arguments.
3018 if (IsTemplateName) {
3019 SourceLocation LAngle, RAngle;
3020 TemplateArgList Args;
3021 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
3024 // TODO: Could inject an invalid typedef decl in an enclosing scope to
3025 // avoid rippling error messages on subsequent uses of the same type,
3026 // could be useful if #include was forgotten.
3027 return true;
3030 /// Determine the declaration specifier context from the declarator
3031 /// context.
3033 /// \param Context the declarator context, which is one of the
3034 /// DeclaratorContext enumerator values.
3035 Parser::DeclSpecContext
3036 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
3037 switch (Context) {
3038 case DeclaratorContext::Member:
3039 return DeclSpecContext::DSC_class;
3040 case DeclaratorContext::File:
3041 return DeclSpecContext::DSC_top_level;
3042 case DeclaratorContext::TemplateParam:
3043 return DeclSpecContext::DSC_template_param;
3044 case DeclaratorContext::TemplateArg:
3045 return DeclSpecContext::DSC_template_arg;
3046 case DeclaratorContext::TemplateTypeArg:
3047 return DeclSpecContext::DSC_template_type_arg;
3048 case DeclaratorContext::TrailingReturn:
3049 case DeclaratorContext::TrailingReturnVar:
3050 return DeclSpecContext::DSC_trailing;
3051 case DeclaratorContext::AliasDecl:
3052 case DeclaratorContext::AliasTemplate:
3053 return DeclSpecContext::DSC_alias_declaration;
3054 case DeclaratorContext::Association:
3055 return DeclSpecContext::DSC_association;
3056 case DeclaratorContext::TypeName:
3057 return DeclSpecContext::DSC_type_specifier;
3058 case DeclaratorContext::Condition:
3059 return DeclSpecContext::DSC_condition;
3060 case DeclaratorContext::ConversionId:
3061 return DeclSpecContext::DSC_conv_operator;
3062 case DeclaratorContext::CXXNew:
3063 return DeclSpecContext::DSC_new;
3064 case DeclaratorContext::Prototype:
3065 case DeclaratorContext::ObjCResult:
3066 case DeclaratorContext::ObjCParameter:
3067 case DeclaratorContext::KNRTypeList:
3068 case DeclaratorContext::FunctionalCast:
3069 case DeclaratorContext::Block:
3070 case DeclaratorContext::ForInit:
3071 case DeclaratorContext::SelectionInit:
3072 case DeclaratorContext::CXXCatch:
3073 case DeclaratorContext::ObjCCatch:
3074 case DeclaratorContext::BlockLiteral:
3075 case DeclaratorContext::LambdaExpr:
3076 case DeclaratorContext::LambdaExprParameter:
3077 case DeclaratorContext::RequiresExpr:
3078 return DeclSpecContext::DSC_normal;
3081 llvm_unreachable("Missing DeclaratorContext case");
3084 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
3086 /// [C11] type-id
3087 /// [C11] constant-expression
3088 /// [C++0x] type-id ...[opt]
3089 /// [C++0x] assignment-expression ...[opt]
3090 ExprResult Parser::ParseAlignArgument(StringRef KWName, SourceLocation Start,
3091 SourceLocation &EllipsisLoc, bool &IsType,
3092 ParsedType &TypeResult) {
3093 ExprResult ER;
3094 if (isTypeIdInParens()) {
3095 SourceLocation TypeLoc = Tok.getLocation();
3096 ParsedType Ty = ParseTypeName().get();
3097 SourceRange TypeRange(Start, Tok.getLocation());
3098 if (Actions.ActOnAlignasTypeArgument(KWName, Ty, TypeLoc, TypeRange))
3099 return ExprError();
3100 TypeResult = Ty;
3101 IsType = true;
3102 } else {
3103 ER = ParseConstantExpression();
3104 IsType = false;
3107 if (getLangOpts().CPlusPlus11)
3108 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3110 return ER;
3113 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
3114 /// attribute to Attrs.
3116 /// alignment-specifier:
3117 /// [C11] '_Alignas' '(' type-id ')'
3118 /// [C11] '_Alignas' '(' constant-expression ')'
3119 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
3120 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
3121 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
3122 SourceLocation *EndLoc) {
3123 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
3124 "Not an alignment-specifier!");
3125 Token KWTok = Tok;
3126 IdentifierInfo *KWName = KWTok.getIdentifierInfo();
3127 auto Kind = KWTok.getKind();
3128 SourceLocation KWLoc = ConsumeToken();
3130 BalancedDelimiterTracker T(*this, tok::l_paren);
3131 if (T.expectAndConsume())
3132 return;
3134 bool IsType;
3135 ParsedType TypeResult;
3136 SourceLocation EllipsisLoc;
3137 ExprResult ArgExpr =
3138 ParseAlignArgument(PP.getSpelling(KWTok), T.getOpenLocation(),
3139 EllipsisLoc, IsType, TypeResult);
3140 if (ArgExpr.isInvalid()) {
3141 T.skipToEnd();
3142 return;
3145 T.consumeClose();
3146 if (EndLoc)
3147 *EndLoc = T.getCloseLocation();
3149 if (IsType) {
3150 Attrs.addNewTypeAttr(KWName, KWLoc, nullptr, KWLoc, TypeResult, Kind,
3151 EllipsisLoc);
3152 } else {
3153 ArgsVector ArgExprs;
3154 ArgExprs.push_back(ArgExpr.get());
3155 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1, Kind,
3156 EllipsisLoc);
3160 ExprResult Parser::ParseExtIntegerArgument() {
3161 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
3162 "Not an extended int type");
3163 ConsumeToken();
3165 BalancedDelimiterTracker T(*this, tok::l_paren);
3166 if (T.expectAndConsume())
3167 return ExprError();
3169 ExprResult ER = ParseConstantExpression();
3170 if (ER.isInvalid()) {
3171 T.skipToEnd();
3172 return ExprError();
3175 if(T.consumeClose())
3176 return ExprError();
3177 return ER;
3180 /// Determine whether we're looking at something that might be a declarator
3181 /// in a simple-declaration. If it can't possibly be a declarator, maybe
3182 /// diagnose a missing semicolon after a prior tag definition in the decl
3183 /// specifier.
3185 /// \return \c true if an error occurred and this can't be any kind of
3186 /// declaration.
3187 bool
3188 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
3189 DeclSpecContext DSContext,
3190 LateParsedAttrList *LateAttrs) {
3191 assert(DS.hasTagDefinition() && "shouldn't call this");
3193 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3194 DSContext == DeclSpecContext::DSC_top_level);
3196 if (getLangOpts().CPlusPlus &&
3197 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
3198 tok::annot_template_id) &&
3199 TryAnnotateCXXScopeToken(EnteringContext)) {
3200 SkipMalformedDecl();
3201 return true;
3204 bool HasScope = Tok.is(tok::annot_cxxscope);
3205 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
3206 Token AfterScope = HasScope ? NextToken() : Tok;
3208 // Determine whether the following tokens could possibly be a
3209 // declarator.
3210 bool MightBeDeclarator = true;
3211 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
3212 // A declarator-id can't start with 'typename'.
3213 MightBeDeclarator = false;
3214 } else if (AfterScope.is(tok::annot_template_id)) {
3215 // If we have a type expressed as a template-id, this cannot be a
3216 // declarator-id (such a type cannot be redeclared in a simple-declaration).
3217 TemplateIdAnnotation *Annot =
3218 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
3219 if (Annot->Kind == TNK_Type_template)
3220 MightBeDeclarator = false;
3221 } else if (AfterScope.is(tok::identifier)) {
3222 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
3224 // These tokens cannot come after the declarator-id in a
3225 // simple-declaration, and are likely to come after a type-specifier.
3226 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
3227 tok::annot_cxxscope, tok::coloncolon)) {
3228 // Missing a semicolon.
3229 MightBeDeclarator = false;
3230 } else if (HasScope) {
3231 // If the declarator-id has a scope specifier, it must redeclare a
3232 // previously-declared entity. If that's a type (and this is not a
3233 // typedef), that's an error.
3234 CXXScopeSpec SS;
3235 Actions.RestoreNestedNameSpecifierAnnotation(
3236 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3237 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
3238 Sema::NameClassification Classification = Actions.ClassifyName(
3239 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
3240 /*CCC=*/nullptr);
3241 switch (Classification.getKind()) {
3242 case Sema::NC_Error:
3243 SkipMalformedDecl();
3244 return true;
3246 case Sema::NC_Keyword:
3247 llvm_unreachable("typo correction is not possible here");
3249 case Sema::NC_Type:
3250 case Sema::NC_TypeTemplate:
3251 case Sema::NC_UndeclaredNonType:
3252 case Sema::NC_UndeclaredTemplate:
3253 // Not a previously-declared non-type entity.
3254 MightBeDeclarator = false;
3255 break;
3257 case Sema::NC_Unknown:
3258 case Sema::NC_NonType:
3259 case Sema::NC_DependentNonType:
3260 case Sema::NC_OverloadSet:
3261 case Sema::NC_VarTemplate:
3262 case Sema::NC_FunctionTemplate:
3263 case Sema::NC_Concept:
3264 // Might be a redeclaration of a prior entity.
3265 break;
3270 if (MightBeDeclarator)
3271 return false;
3273 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
3274 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
3275 diag::err_expected_after)
3276 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
3278 // Try to recover from the typo, by dropping the tag definition and parsing
3279 // the problematic tokens as a type.
3281 // FIXME: Split the DeclSpec into pieces for the standalone
3282 // declaration and pieces for the following declaration, instead
3283 // of assuming that all the other pieces attach to new declaration,
3284 // and call ParsedFreeStandingDeclSpec as appropriate.
3285 DS.ClearTypeSpecType();
3286 ParsedTemplateInfo NotATemplate;
3287 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
3288 return false;
3291 // Choose the apprpriate diagnostic error for why fixed point types are
3292 // disabled, set the previous specifier, and mark as invalid.
3293 static void SetupFixedPointError(const LangOptions &LangOpts,
3294 const char *&PrevSpec, unsigned &DiagID,
3295 bool &isInvalid) {
3296 assert(!LangOpts.FixedPoint);
3297 DiagID = diag::err_fixed_point_not_enabled;
3298 PrevSpec = ""; // Not used by diagnostic
3299 isInvalid = true;
3302 /// ParseDeclarationSpecifiers
3303 /// declaration-specifiers: [C99 6.7]
3304 /// storage-class-specifier declaration-specifiers[opt]
3305 /// type-specifier declaration-specifiers[opt]
3306 /// [C99] function-specifier declaration-specifiers[opt]
3307 /// [C11] alignment-specifier declaration-specifiers[opt]
3308 /// [GNU] attributes declaration-specifiers[opt]
3309 /// [Clang] '__module_private__' declaration-specifiers[opt]
3310 /// [ObjC1] '__kindof' declaration-specifiers[opt]
3312 /// storage-class-specifier: [C99 6.7.1]
3313 /// 'typedef'
3314 /// 'extern'
3315 /// 'static'
3316 /// 'auto'
3317 /// 'register'
3318 /// [C++] 'mutable'
3319 /// [C++11] 'thread_local'
3320 /// [C11] '_Thread_local'
3321 /// [GNU] '__thread'
3322 /// function-specifier: [C99 6.7.4]
3323 /// [C99] 'inline'
3324 /// [C++] 'virtual'
3325 /// [C++] 'explicit'
3326 /// [OpenCL] '__kernel'
3327 /// 'friend': [C++ dcl.friend]
3328 /// 'constexpr': [C++0x dcl.constexpr]
3329 void Parser::ParseDeclarationSpecifiers(
3330 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
3331 DeclSpecContext DSContext, LateParsedAttrList *LateAttrs,
3332 ImplicitTypenameContext AllowImplicitTypename) {
3333 if (DS.getSourceRange().isInvalid()) {
3334 // Start the range at the current token but make the end of the range
3335 // invalid. This will make the entire range invalid unless we successfully
3336 // consume a token.
3337 DS.SetRangeStart(Tok.getLocation());
3338 DS.SetRangeEnd(SourceLocation());
3341 // If we are in a operator context, convert it back into a type specifier
3342 // context for better error handling later on.
3343 if (DSContext == DeclSpecContext::DSC_conv_operator) {
3344 // No implicit typename here.
3345 AllowImplicitTypename = ImplicitTypenameContext::No;
3346 DSContext = DeclSpecContext::DSC_type_specifier;
3349 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3350 DSContext == DeclSpecContext::DSC_top_level);
3351 bool AttrsLastTime = false;
3352 ParsedAttributes attrs(AttrFactory);
3353 // We use Sema's policy to get bool macros right.
3354 PrintingPolicy Policy = Actions.getPrintingPolicy();
3355 while (true) {
3356 bool isInvalid = false;
3357 bool isStorageClass = false;
3358 const char *PrevSpec = nullptr;
3359 unsigned DiagID = 0;
3361 // This value needs to be set to the location of the last token if the last
3362 // token of the specifier is already consumed.
3363 SourceLocation ConsumedEnd;
3365 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3366 // implementation for VS2013 uses _Atomic as an identifier for one of the
3367 // classes in <atomic>.
3369 // A typedef declaration containing _Atomic<...> is among the places where
3370 // the class is used. If we are currently parsing such a declaration, treat
3371 // the token as an identifier.
3372 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3373 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3374 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3375 Tok.setKind(tok::identifier);
3377 SourceLocation Loc = Tok.getLocation();
3379 // Helper for image types in OpenCL.
3380 auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
3381 // Check if the image type is supported and otherwise turn the keyword into an identifier
3382 // because image types from extensions are not reserved identifiers.
3383 if (!StringRef(Ext).empty() && !getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())) {
3384 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3385 Tok.setKind(tok::identifier);
3386 return false;
3388 isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3389 return true;
3392 // Turn off usual access checking for template specializations and
3393 // instantiations.
3394 bool IsTemplateSpecOrInst =
3395 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3396 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3398 switch (Tok.getKind()) {
3399 default:
3400 if (Tok.isRegularKeywordAttribute())
3401 goto Attribute;
3403 DoneWithDeclSpec:
3404 if (!AttrsLastTime)
3405 ProhibitAttributes(attrs);
3406 else {
3407 // Reject C++11 / C23 attributes that aren't type attributes.
3408 for (const ParsedAttr &PA : attrs) {
3409 if (!PA.isCXX11Attribute() && !PA.isC23Attribute() &&
3410 !PA.isRegularKeywordAttribute())
3411 continue;
3412 if (PA.getKind() == ParsedAttr::UnknownAttribute)
3413 // We will warn about the unknown attribute elsewhere (in
3414 // SemaDeclAttr.cpp)
3415 continue;
3416 // GCC ignores this attribute when placed on the DeclSpec in [[]]
3417 // syntax, so we do the same.
3418 if (PA.getKind() == ParsedAttr::AT_VectorSize) {
3419 Diag(PA.getLoc(), diag::warn_attribute_ignored) << PA;
3420 PA.setInvalid();
3421 continue;
3423 // We reject AT_LifetimeBound and AT_AnyX86NoCfCheck, even though they
3424 // are type attributes, because we historically haven't allowed these
3425 // to be used as type attributes in C++11 / C23 syntax.
3426 if (PA.isTypeAttr() && PA.getKind() != ParsedAttr::AT_LifetimeBound &&
3427 PA.getKind() != ParsedAttr::AT_AnyX86NoCfCheck)
3428 continue;
3429 Diag(PA.getLoc(), diag::err_attribute_not_type_attr)
3430 << PA << PA.isRegularKeywordAttribute();
3431 PA.setInvalid();
3434 DS.takeAttributesFrom(attrs);
3437 // If this is not a declaration specifier token, we're done reading decl
3438 // specifiers. First verify that DeclSpec's are consistent.
3439 DS.Finish(Actions, Policy);
3440 return;
3442 case tok::l_square:
3443 case tok::kw_alignas:
3444 if (!isAllowedCXX11AttributeSpecifier())
3445 goto DoneWithDeclSpec;
3447 Attribute:
3448 ProhibitAttributes(attrs);
3449 // FIXME: It would be good to recover by accepting the attributes,
3450 // but attempting to do that now would cause serious
3451 // madness in terms of diagnostics.
3452 attrs.clear();
3453 attrs.Range = SourceRange();
3455 ParseCXX11Attributes(attrs);
3456 AttrsLastTime = true;
3457 continue;
3459 case tok::code_completion: {
3460 Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
3461 if (DS.hasTypeSpecifier()) {
3462 bool AllowNonIdentifiers
3463 = (getCurScope()->getFlags() & (Scope::ControlScope |
3464 Scope::BlockScope |
3465 Scope::TemplateParamScope |
3466 Scope::FunctionPrototypeScope |
3467 Scope::AtCatchScope)) == 0;
3468 bool AllowNestedNameSpecifiers
3469 = DSContext == DeclSpecContext::DSC_top_level ||
3470 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3472 cutOffParsing();
3473 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3474 AllowNonIdentifiers,
3475 AllowNestedNameSpecifiers);
3476 return;
3479 // Class context can appear inside a function/block, so prioritise that.
3480 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3481 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3482 : Sema::PCC_Template;
3483 else if (DSContext == DeclSpecContext::DSC_class)
3484 CCC = Sema::PCC_Class;
3485 else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3486 CCC = Sema::PCC_LocalDeclarationSpecifiers;
3487 else if (CurParsedObjCImpl)
3488 CCC = Sema::PCC_ObjCImplementation;
3490 cutOffParsing();
3491 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3492 return;
3495 case tok::coloncolon: // ::foo::bar
3496 // C++ scope specifier. Annotate and loop, or bail out on error.
3497 if (TryAnnotateCXXScopeToken(EnteringContext)) {
3498 if (!DS.hasTypeSpecifier())
3499 DS.SetTypeSpecError();
3500 goto DoneWithDeclSpec;
3502 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3503 goto DoneWithDeclSpec;
3504 continue;
3506 case tok::annot_cxxscope: {
3507 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3508 goto DoneWithDeclSpec;
3510 CXXScopeSpec SS;
3511 if (TemplateInfo.TemplateParams)
3512 SS.setTemplateParamLists(*TemplateInfo.TemplateParams);
3513 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3514 Tok.getAnnotationRange(),
3515 SS);
3517 // We are looking for a qualified typename.
3518 Token Next = NextToken();
3520 TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3521 ? takeTemplateIdAnnotation(Next)
3522 : nullptr;
3523 if (TemplateId && TemplateId->hasInvalidName()) {
3524 // We found something like 'T::U<Args> x', but U is not a template.
3525 // Assume it was supposed to be a type.
3526 DS.SetTypeSpecError();
3527 ConsumeAnnotationToken();
3528 break;
3531 if (TemplateId && TemplateId->Kind == TNK_Type_template) {
3532 // We have a qualified template-id, e.g., N::A<int>
3534 // If this would be a valid constructor declaration with template
3535 // arguments, we will reject the attempt to form an invalid type-id
3536 // referring to the injected-class-name when we annotate the token,
3537 // per C++ [class.qual]p2.
3539 // To improve diagnostics for this case, parse the declaration as a
3540 // constructor (and reject the extra template arguments later).
3541 if ((DSContext == DeclSpecContext::DSC_top_level ||
3542 DSContext == DeclSpecContext::DSC_class) &&
3543 TemplateId->Name &&
3544 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3545 isConstructorDeclarator(/*Unqualified=*/false,
3546 /*DeductionGuide=*/false,
3547 DS.isFriendSpecified())) {
3548 // The user meant this to be an out-of-line constructor
3549 // definition, but template arguments are not allowed
3550 // there. Just allow this as a constructor; we'll
3551 // complain about it later.
3552 goto DoneWithDeclSpec;
3555 DS.getTypeSpecScope() = SS;
3556 ConsumeAnnotationToken(); // The C++ scope.
3557 assert(Tok.is(tok::annot_template_id) &&
3558 "ParseOptionalCXXScopeSpecifier not working");
3559 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3560 continue;
3563 if (TemplateId && TemplateId->Kind == TNK_Concept_template) {
3564 DS.getTypeSpecScope() = SS;
3565 // This is probably a qualified placeholder-specifier, e.g., ::C<int>
3566 // auto ... Consume the scope annotation and continue to consume the
3567 // template-id as a placeholder-specifier. Let the next iteration
3568 // diagnose a missing auto.
3569 ConsumeAnnotationToken();
3570 continue;
3573 if (Next.is(tok::annot_typename)) {
3574 DS.getTypeSpecScope() = SS;
3575 ConsumeAnnotationToken(); // The C++ scope.
3576 TypeResult T = getTypeAnnotation(Tok);
3577 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3578 Tok.getAnnotationEndLoc(),
3579 PrevSpec, DiagID, T, Policy);
3580 if (isInvalid)
3581 break;
3582 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3583 ConsumeAnnotationToken(); // The typename
3586 if (AllowImplicitTypename == ImplicitTypenameContext::Yes &&
3587 Next.is(tok::annot_template_id) &&
3588 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3589 ->Kind == TNK_Dependent_template_name) {
3590 DS.getTypeSpecScope() = SS;
3591 ConsumeAnnotationToken(); // The C++ scope.
3592 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3593 continue;
3596 if (Next.isNot(tok::identifier))
3597 goto DoneWithDeclSpec;
3599 // Check whether this is a constructor declaration. If we're in a
3600 // context where the identifier could be a class name, and it has the
3601 // shape of a constructor declaration, process it as one.
3602 if ((DSContext == DeclSpecContext::DSC_top_level ||
3603 DSContext == DeclSpecContext::DSC_class) &&
3604 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3605 &SS) &&
3606 isConstructorDeclarator(/*Unqualified=*/false,
3607 /*DeductionGuide=*/false,
3608 DS.isFriendSpecified(),
3609 &TemplateInfo))
3610 goto DoneWithDeclSpec;
3612 // C++20 [temp.spec] 13.9/6.
3613 // This disables the access checking rules for function template explicit
3614 // instantiation and explicit specialization:
3615 // - `return type`.
3616 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3618 ParsedType TypeRep = Actions.getTypeName(
3619 *Next.getIdentifierInfo(), Next.getLocation(), getCurScope(), &SS,
3620 false, false, nullptr,
3621 /*IsCtorOrDtorName=*/false,
3622 /*WantNontrivialTypeSourceInfo=*/true,
3623 isClassTemplateDeductionContext(DSContext), AllowImplicitTypename);
3625 if (IsTemplateSpecOrInst)
3626 SAC.done();
3628 // If the referenced identifier is not a type, then this declspec is
3629 // erroneous: We already checked about that it has no type specifier, and
3630 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3631 // typename.
3632 if (!TypeRep) {
3633 if (TryAnnotateTypeConstraint())
3634 goto DoneWithDeclSpec;
3635 if (Tok.isNot(tok::annot_cxxscope) ||
3636 NextToken().isNot(tok::identifier))
3637 continue;
3638 // Eat the scope spec so the identifier is current.
3639 ConsumeAnnotationToken();
3640 ParsedAttributes Attrs(AttrFactory);
3641 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3642 if (!Attrs.empty()) {
3643 AttrsLastTime = true;
3644 attrs.takeAllFrom(Attrs);
3646 continue;
3648 goto DoneWithDeclSpec;
3651 DS.getTypeSpecScope() = SS;
3652 ConsumeAnnotationToken(); // The C++ scope.
3654 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3655 DiagID, TypeRep, Policy);
3656 if (isInvalid)
3657 break;
3659 DS.SetRangeEnd(Tok.getLocation());
3660 ConsumeToken(); // The typename.
3662 continue;
3665 case tok::annot_typename: {
3666 // If we've previously seen a tag definition, we were almost surely
3667 // missing a semicolon after it.
3668 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3669 goto DoneWithDeclSpec;
3671 TypeResult T = getTypeAnnotation(Tok);
3672 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3673 DiagID, T, Policy);
3674 if (isInvalid)
3675 break;
3677 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3678 ConsumeAnnotationToken(); // The typename
3680 continue;
3683 case tok::kw___is_signed:
3684 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3685 // typically treats it as a trait. If we see __is_signed as it appears
3686 // in libstdc++, e.g.,
3688 // static const bool __is_signed;
3690 // then treat __is_signed as an identifier rather than as a keyword.
3691 if (DS.getTypeSpecType() == TST_bool &&
3692 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3693 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3694 TryKeywordIdentFallback(true);
3696 // We're done with the declaration-specifiers.
3697 goto DoneWithDeclSpec;
3699 // typedef-name
3700 case tok::kw___super:
3701 case tok::kw_decltype:
3702 case tok::identifier:
3703 ParseIdentifier: {
3704 // This identifier can only be a typedef name if we haven't already seen
3705 // a type-specifier. Without this check we misparse:
3706 // typedef int X; struct Y { short X; }; as 'short int'.
3707 if (DS.hasTypeSpecifier())
3708 goto DoneWithDeclSpec;
3710 // If the token is an identifier named "__declspec" and Microsoft
3711 // extensions are not enabled, it is likely that there will be cascading
3712 // parse errors if this really is a __declspec attribute. Attempt to
3713 // recognize that scenario and recover gracefully.
3714 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3715 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3716 Diag(Loc, diag::err_ms_attributes_not_enabled);
3718 // The next token should be an open paren. If it is, eat the entire
3719 // attribute declaration and continue.
3720 if (NextToken().is(tok::l_paren)) {
3721 // Consume the __declspec identifier.
3722 ConsumeToken();
3724 // Eat the parens and everything between them.
3725 BalancedDelimiterTracker T(*this, tok::l_paren);
3726 if (T.consumeOpen()) {
3727 assert(false && "Not a left paren?");
3728 return;
3730 T.skipToEnd();
3731 continue;
3735 // In C++, check to see if this is a scope specifier like foo::bar::, if
3736 // so handle it as such. This is important for ctor parsing.
3737 if (getLangOpts().CPlusPlus) {
3738 // C++20 [temp.spec] 13.9/6.
3739 // This disables the access checking rules for function template
3740 // explicit instantiation and explicit specialization:
3741 // - `return type`.
3742 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3744 const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
3746 if (IsTemplateSpecOrInst)
3747 SAC.done();
3749 if (Success) {
3750 if (IsTemplateSpecOrInst)
3751 SAC.redelay();
3752 DS.SetTypeSpecError();
3753 goto DoneWithDeclSpec;
3756 if (!Tok.is(tok::identifier))
3757 continue;
3760 // Check for need to substitute AltiVec keyword tokens.
3761 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3762 break;
3764 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3765 // allow the use of a typedef name as a type specifier.
3766 if (DS.isTypeAltiVecVector())
3767 goto DoneWithDeclSpec;
3769 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3770 isObjCInstancetype()) {
3771 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3772 assert(TypeRep);
3773 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3774 DiagID, TypeRep, Policy);
3775 if (isInvalid)
3776 break;
3778 DS.SetRangeEnd(Loc);
3779 ConsumeToken();
3780 continue;
3783 // If we're in a context where the identifier could be a class name,
3784 // check whether this is a constructor declaration.
3785 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3786 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3787 isConstructorDeclarator(/*Unqualified=*/true,
3788 /*DeductionGuide=*/false,
3789 DS.isFriendSpecified()))
3790 goto DoneWithDeclSpec;
3792 ParsedType TypeRep = Actions.getTypeName(
3793 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3794 false, false, nullptr, false, false,
3795 isClassTemplateDeductionContext(DSContext));
3797 // If this is not a typedef name, don't parse it as part of the declspec,
3798 // it must be an implicit int or an error.
3799 if (!TypeRep) {
3800 if (TryAnnotateTypeConstraint())
3801 goto DoneWithDeclSpec;
3802 if (Tok.isNot(tok::identifier))
3803 continue;
3804 ParsedAttributes Attrs(AttrFactory);
3805 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3806 if (!Attrs.empty()) {
3807 AttrsLastTime = true;
3808 attrs.takeAllFrom(Attrs);
3810 continue;
3812 goto DoneWithDeclSpec;
3815 // Likewise, if this is a context where the identifier could be a template
3816 // name, check whether this is a deduction guide declaration.
3817 CXXScopeSpec SS;
3818 if (getLangOpts().CPlusPlus17 &&
3819 (DSContext == DeclSpecContext::DSC_class ||
3820 DSContext == DeclSpecContext::DSC_top_level) &&
3821 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3822 Tok.getLocation(), SS) &&
3823 isConstructorDeclarator(/*Unqualified*/ true,
3824 /*DeductionGuide*/ true))
3825 goto DoneWithDeclSpec;
3827 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3828 DiagID, TypeRep, Policy);
3829 if (isInvalid)
3830 break;
3832 DS.SetRangeEnd(Tok.getLocation());
3833 ConsumeToken(); // The identifier
3835 // Objective-C supports type arguments and protocol references
3836 // following an Objective-C object or object pointer
3837 // type. Handle either one of them.
3838 if (Tok.is(tok::less) && getLangOpts().ObjC) {
3839 SourceLocation NewEndLoc;
3840 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3841 Loc, TypeRep, /*consumeLastToken=*/true,
3842 NewEndLoc);
3843 if (NewTypeRep.isUsable()) {
3844 DS.UpdateTypeRep(NewTypeRep.get());
3845 DS.SetRangeEnd(NewEndLoc);
3849 // Need to support trailing type qualifiers (e.g. "id<p> const").
3850 // If a type specifier follows, it will be diagnosed elsewhere.
3851 continue;
3854 // type-name or placeholder-specifier
3855 case tok::annot_template_id: {
3856 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3858 if (TemplateId->hasInvalidName()) {
3859 DS.SetTypeSpecError();
3860 break;
3863 if (TemplateId->Kind == TNK_Concept_template) {
3864 // If we've already diagnosed that this type-constraint has invalid
3865 // arguments, drop it and just form 'auto' or 'decltype(auto)'.
3866 if (TemplateId->hasInvalidArgs())
3867 TemplateId = nullptr;
3869 // Any of the following tokens are likely the start of the user
3870 // forgetting 'auto' or 'decltype(auto)', so diagnose.
3871 // Note: if updating this list, please make sure we update
3872 // isCXXDeclarationSpecifier's check for IsPlaceholderSpecifier to have
3873 // a matching list.
3874 if (NextToken().isOneOf(tok::identifier, tok::kw_const,
3875 tok::kw_volatile, tok::kw_restrict, tok::amp,
3876 tok::ampamp)) {
3877 Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3878 << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3879 // Attempt to continue as if 'auto' was placed here.
3880 isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3881 TemplateId, Policy);
3882 break;
3884 if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3885 goto DoneWithDeclSpec;
3887 if (TemplateId && !isInvalid && Actions.CheckTypeConstraint(TemplateId))
3888 TemplateId = nullptr;
3890 ConsumeAnnotationToken();
3891 SourceLocation AutoLoc = Tok.getLocation();
3892 if (TryConsumeToken(tok::kw_decltype)) {
3893 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3894 if (Tracker.consumeOpen()) {
3895 // Something like `void foo(Iterator decltype i)`
3896 Diag(Tok, diag::err_expected) << tok::l_paren;
3897 } else {
3898 if (!TryConsumeToken(tok::kw_auto)) {
3899 // Something like `void foo(Iterator decltype(int) i)`
3900 Tracker.skipToEnd();
3901 Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3902 << FixItHint::CreateReplacement(SourceRange(AutoLoc,
3903 Tok.getLocation()),
3904 "auto");
3905 } else {
3906 Tracker.consumeClose();
3909 ConsumedEnd = Tok.getLocation();
3910 DS.setTypeArgumentRange(Tracker.getRange());
3911 // Even if something went wrong above, continue as if we've seen
3912 // `decltype(auto)`.
3913 isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3914 DiagID, TemplateId, Policy);
3915 } else {
3916 isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
3917 TemplateId, Policy);
3919 break;
3922 if (TemplateId->Kind != TNK_Type_template &&
3923 TemplateId->Kind != TNK_Undeclared_template) {
3924 // This template-id does not refer to a type name, so we're
3925 // done with the type-specifiers.
3926 goto DoneWithDeclSpec;
3929 // If we're in a context where the template-id could be a
3930 // constructor name or specialization, check whether this is a
3931 // constructor declaration.
3932 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3933 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3934 isConstructorDeclarator(/*Unqualified=*/true,
3935 /*DeductionGuide=*/false,
3936 DS.isFriendSpecified()))
3937 goto DoneWithDeclSpec;
3939 // Turn the template-id annotation token into a type annotation
3940 // token, then try again to parse it as a type-specifier.
3941 CXXScopeSpec SS;
3942 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3943 continue;
3946 // Attributes support.
3947 case tok::kw___attribute:
3948 case tok::kw___declspec:
3949 ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), LateAttrs);
3950 continue;
3952 // Microsoft single token adornments.
3953 case tok::kw___forceinline: {
3954 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3955 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3956 SourceLocation AttrNameLoc = Tok.getLocation();
3957 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3958 nullptr, 0, tok::kw___forceinline);
3959 break;
3962 case tok::kw___unaligned:
3963 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3964 getLangOpts());
3965 break;
3967 case tok::kw___sptr:
3968 case tok::kw___uptr:
3969 case tok::kw___ptr64:
3970 case tok::kw___ptr32:
3971 case tok::kw___w64:
3972 case tok::kw___cdecl:
3973 case tok::kw___stdcall:
3974 case tok::kw___fastcall:
3975 case tok::kw___thiscall:
3976 case tok::kw___regcall:
3977 case tok::kw___vectorcall:
3978 ParseMicrosoftTypeAttributes(DS.getAttributes());
3979 continue;
3981 case tok::kw___funcref:
3982 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
3983 continue;
3985 // Borland single token adornments.
3986 case tok::kw___pascal:
3987 ParseBorlandTypeAttributes(DS.getAttributes());
3988 continue;
3990 // OpenCL single token adornments.
3991 case tok::kw___kernel:
3992 ParseOpenCLKernelAttributes(DS.getAttributes());
3993 continue;
3995 // CUDA/HIP single token adornments.
3996 case tok::kw___noinline__:
3997 ParseCUDAFunctionAttributes(DS.getAttributes());
3998 continue;
4000 // Nullability type specifiers.
4001 case tok::kw__Nonnull:
4002 case tok::kw__Nullable:
4003 case tok::kw__Nullable_result:
4004 case tok::kw__Null_unspecified:
4005 ParseNullabilityTypeSpecifiers(DS.getAttributes());
4006 continue;
4008 // Objective-C 'kindof' types.
4009 case tok::kw___kindof:
4010 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
4011 nullptr, 0, tok::kw___kindof);
4012 (void)ConsumeToken();
4013 continue;
4015 // storage-class-specifier
4016 case tok::kw_typedef:
4017 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
4018 PrevSpec, DiagID, Policy);
4019 isStorageClass = true;
4020 break;
4021 case tok::kw_extern:
4022 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
4023 Diag(Tok, diag::ext_thread_before) << "extern";
4024 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
4025 PrevSpec, DiagID, Policy);
4026 isStorageClass = true;
4027 break;
4028 case tok::kw___private_extern__:
4029 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
4030 Loc, PrevSpec, DiagID, Policy);
4031 isStorageClass = true;
4032 break;
4033 case tok::kw_static:
4034 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
4035 Diag(Tok, diag::ext_thread_before) << "static";
4036 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
4037 PrevSpec, DiagID, Policy);
4038 isStorageClass = true;
4039 break;
4040 case tok::kw_auto:
4041 if (getLangOpts().CPlusPlus11 || getLangOpts().C23) {
4042 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
4043 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
4044 PrevSpec, DiagID, Policy);
4045 if (!isInvalid && !getLangOpts().C23)
4046 Diag(Tok, diag::ext_auto_storage_class)
4047 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4048 } else
4049 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
4050 DiagID, Policy);
4051 } else
4052 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
4053 PrevSpec, DiagID, Policy);
4054 isStorageClass = true;
4055 break;
4056 case tok::kw___auto_type:
4057 Diag(Tok, diag::ext_auto_type);
4058 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
4059 DiagID, Policy);
4060 break;
4061 case tok::kw_register:
4062 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
4063 PrevSpec, DiagID, Policy);
4064 isStorageClass = true;
4065 break;
4066 case tok::kw_mutable:
4067 isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
4068 PrevSpec, DiagID, Policy);
4069 isStorageClass = true;
4070 break;
4071 case tok::kw___thread:
4072 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
4073 PrevSpec, DiagID);
4074 isStorageClass = true;
4075 break;
4076 case tok::kw_thread_local:
4077 if (getLangOpts().C23)
4078 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4079 // We map thread_local to _Thread_local in C23 mode so it retains the C
4080 // semantics rather than getting the C++ semantics.
4081 // FIXME: diagnostics will show _Thread_local when the user wrote
4082 // thread_local in source in C23 mode; we need some general way to
4083 // identify which way the user spelled the keyword in source.
4084 isInvalid = DS.SetStorageClassSpecThread(
4085 getLangOpts().C23 ? DeclSpec::TSCS__Thread_local
4086 : DeclSpec::TSCS_thread_local,
4087 Loc, PrevSpec, DiagID);
4088 isStorageClass = true;
4089 break;
4090 case tok::kw__Thread_local:
4091 if (!getLangOpts().C11)
4092 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4093 isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
4094 Loc, PrevSpec, DiagID);
4095 isStorageClass = true;
4096 break;
4098 // function-specifier
4099 case tok::kw_inline:
4100 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
4101 break;
4102 case tok::kw_virtual:
4103 // C++ for OpenCL does not allow virtual function qualifier, to avoid
4104 // function pointers restricted in OpenCL v2.0 s6.9.a.
4105 if (getLangOpts().OpenCLCPlusPlus &&
4106 !getActions().getOpenCLOptions().isAvailableOption(
4107 "__cl_clang_function_pointers", getLangOpts())) {
4108 DiagID = diag::err_openclcxx_virtual_function;
4109 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4110 isInvalid = true;
4111 } else {
4112 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
4114 break;
4115 case tok::kw_explicit: {
4116 SourceLocation ExplicitLoc = Loc;
4117 SourceLocation CloseParenLoc;
4118 ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
4119 ConsumedEnd = ExplicitLoc;
4120 ConsumeToken(); // kw_explicit
4121 if (Tok.is(tok::l_paren)) {
4122 if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
4123 Diag(Tok.getLocation(), getLangOpts().CPlusPlus20
4124 ? diag::warn_cxx17_compat_explicit_bool
4125 : diag::ext_explicit_bool);
4127 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
4128 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4129 Tracker.consumeOpen();
4131 EnterExpressionEvaluationContext ConstantEvaluated(
4132 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4134 ExplicitExpr = ParseConstantExpressionInExprEvalContext();
4135 ConsumedEnd = Tok.getLocation();
4136 if (ExplicitExpr.isUsable()) {
4137 CloseParenLoc = Tok.getLocation();
4138 Tracker.consumeClose();
4139 ExplicitSpec =
4140 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
4141 } else
4142 Tracker.skipToEnd();
4143 } else {
4144 Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
4147 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
4148 ExplicitSpec, CloseParenLoc);
4149 break;
4151 case tok::kw__Noreturn:
4152 if (!getLangOpts().C11)
4153 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4154 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
4155 break;
4157 // alignment-specifier
4158 case tok::kw__Alignas:
4159 if (!getLangOpts().C11)
4160 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4161 ParseAlignmentSpecifier(DS.getAttributes());
4162 continue;
4164 // friend
4165 case tok::kw_friend:
4166 if (DSContext == DeclSpecContext::DSC_class)
4167 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
4168 else {
4169 PrevSpec = ""; // not actually used by the diagnostic
4170 DiagID = diag::err_friend_invalid_in_context;
4171 isInvalid = true;
4173 break;
4175 // Modules
4176 case tok::kw___module_private__:
4177 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
4178 break;
4180 // constexpr, consteval, constinit specifiers
4181 case tok::kw_constexpr:
4182 isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, Loc,
4183 PrevSpec, DiagID);
4184 break;
4185 case tok::kw_consteval:
4186 isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Consteval, Loc,
4187 PrevSpec, DiagID);
4188 break;
4189 case tok::kw_constinit:
4190 isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constinit, Loc,
4191 PrevSpec, DiagID);
4192 break;
4194 // type-specifier
4195 case tok::kw_short:
4196 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec,
4197 DiagID, Policy);
4198 break;
4199 case tok::kw_long:
4200 if (DS.getTypeSpecWidth() != TypeSpecifierWidth::Long)
4201 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec,
4202 DiagID, Policy);
4203 else
4204 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
4205 PrevSpec, DiagID, Policy);
4206 break;
4207 case tok::kw___int64:
4208 isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
4209 PrevSpec, DiagID, Policy);
4210 break;
4211 case tok::kw_signed:
4212 isInvalid =
4213 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4214 break;
4215 case tok::kw_unsigned:
4216 isInvalid = DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec,
4217 DiagID);
4218 break;
4219 case tok::kw__Complex:
4220 if (!getLangOpts().C99)
4221 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4222 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
4223 DiagID);
4224 break;
4225 case tok::kw__Imaginary:
4226 if (!getLangOpts().C99)
4227 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4228 isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
4229 DiagID);
4230 break;
4231 case tok::kw_void:
4232 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
4233 DiagID, Policy);
4234 break;
4235 case tok::kw_char:
4236 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
4237 DiagID, Policy);
4238 break;
4239 case tok::kw_int:
4240 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
4241 DiagID, Policy);
4242 break;
4243 case tok::kw__ExtInt:
4244 case tok::kw__BitInt: {
4245 DiagnoseBitIntUse(Tok);
4246 ExprResult ER = ParseExtIntegerArgument();
4247 if (ER.isInvalid())
4248 continue;
4249 isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
4250 ConsumedEnd = PrevTokLocation;
4251 break;
4253 case tok::kw___int128:
4254 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
4255 DiagID, Policy);
4256 break;
4257 case tok::kw_half:
4258 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
4259 DiagID, Policy);
4260 break;
4261 case tok::kw___bf16:
4262 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec,
4263 DiagID, Policy);
4264 break;
4265 case tok::kw_float:
4266 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
4267 DiagID, Policy);
4268 break;
4269 case tok::kw_double:
4270 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
4271 DiagID, Policy);
4272 break;
4273 case tok::kw__Float16:
4274 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
4275 DiagID, Policy);
4276 break;
4277 case tok::kw__Accum:
4278 if (!getLangOpts().FixedPoint) {
4279 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4280 } else {
4281 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
4282 DiagID, Policy);
4284 break;
4285 case tok::kw__Fract:
4286 if (!getLangOpts().FixedPoint) {
4287 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4288 } else {
4289 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
4290 DiagID, Policy);
4292 break;
4293 case tok::kw__Sat:
4294 if (!getLangOpts().FixedPoint) {
4295 SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4296 } else {
4297 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
4299 break;
4300 case tok::kw___float128:
4301 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
4302 DiagID, Policy);
4303 break;
4304 case tok::kw___ibm128:
4305 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec,
4306 DiagID, Policy);
4307 break;
4308 case tok::kw_wchar_t:
4309 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
4310 DiagID, Policy);
4311 break;
4312 case tok::kw_char8_t:
4313 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
4314 DiagID, Policy);
4315 break;
4316 case tok::kw_char16_t:
4317 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
4318 DiagID, Policy);
4319 break;
4320 case tok::kw_char32_t:
4321 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
4322 DiagID, Policy);
4323 break;
4324 case tok::kw_bool:
4325 if (getLangOpts().C23)
4326 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4327 [[fallthrough]];
4328 case tok::kw__Bool:
4329 if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
4330 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4332 if (Tok.is(tok::kw_bool) &&
4333 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
4334 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
4335 PrevSpec = ""; // Not used by the diagnostic.
4336 DiagID = diag::err_bool_redeclaration;
4337 // For better error recovery.
4338 Tok.setKind(tok::identifier);
4339 isInvalid = true;
4340 } else {
4341 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
4342 DiagID, Policy);
4344 break;
4345 case tok::kw__Decimal32:
4346 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
4347 DiagID, Policy);
4348 break;
4349 case tok::kw__Decimal64:
4350 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
4351 DiagID, Policy);
4352 break;
4353 case tok::kw__Decimal128:
4354 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
4355 DiagID, Policy);
4356 break;
4357 case tok::kw___vector:
4358 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4359 break;
4360 case tok::kw___pixel:
4361 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4362 break;
4363 case tok::kw___bool:
4364 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4365 break;
4366 case tok::kw_pipe:
4367 if (!getLangOpts().OpenCL ||
4368 getLangOpts().getOpenCLCompatibleVersion() < 200) {
4369 // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4370 // should support the "pipe" word as identifier.
4371 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
4372 Tok.setKind(tok::identifier);
4373 goto DoneWithDeclSpec;
4374 } else if (!getLangOpts().OpenCLPipes) {
4375 DiagID = diag::err_opencl_unknown_type_specifier;
4376 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4377 isInvalid = true;
4378 } else
4379 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4380 break;
4381 // We only need to enumerate each image type once.
4382 #define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4383 #define IMAGE_WRITE_TYPE(Type, Id, Ext)
4384 #define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4385 case tok::kw_##ImgType##_t: \
4386 if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4387 goto DoneWithDeclSpec; \
4388 break;
4389 #include "clang/Basic/OpenCLImageTypes.def"
4390 case tok::kw___unknown_anytype:
4391 isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
4392 PrevSpec, DiagID, Policy);
4393 break;
4395 // class-specifier:
4396 case tok::kw_class:
4397 case tok::kw_struct:
4398 case tok::kw___interface:
4399 case tok::kw_union: {
4400 tok::TokenKind Kind = Tok.getKind();
4401 ConsumeToken();
4403 // These are attributes following class specifiers.
4404 // To produce better diagnostic, we parse them when
4405 // parsing class specifier.
4406 ParsedAttributes Attributes(AttrFactory);
4407 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4408 EnteringContext, DSContext, Attributes);
4410 // If there are attributes following class specifier,
4411 // take them over and handle them here.
4412 if (!Attributes.empty()) {
4413 AttrsLastTime = true;
4414 attrs.takeAllFrom(Attributes);
4416 continue;
4419 // enum-specifier:
4420 case tok::kw_enum:
4421 ConsumeToken();
4422 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4423 continue;
4425 // cv-qualifier:
4426 case tok::kw_const:
4427 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4428 getLangOpts());
4429 break;
4430 case tok::kw_volatile:
4431 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4432 getLangOpts());
4433 break;
4434 case tok::kw_restrict:
4435 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4436 getLangOpts());
4437 break;
4439 // C++ typename-specifier:
4440 case tok::kw_typename:
4441 if (TryAnnotateTypeOrScopeToken()) {
4442 DS.SetTypeSpecError();
4443 goto DoneWithDeclSpec;
4445 if (!Tok.is(tok::kw_typename))
4446 continue;
4447 break;
4449 // C23/GNU typeof support.
4450 case tok::kw_typeof:
4451 case tok::kw_typeof_unqual:
4452 ParseTypeofSpecifier(DS);
4453 continue;
4455 case tok::annot_decltype:
4456 ParseDecltypeSpecifier(DS);
4457 continue;
4459 case tok::annot_pragma_pack:
4460 HandlePragmaPack();
4461 continue;
4463 case tok::annot_pragma_ms_pragma:
4464 HandlePragmaMSPragma();
4465 continue;
4467 case tok::annot_pragma_ms_vtordisp:
4468 HandlePragmaMSVtorDisp();
4469 continue;
4471 case tok::annot_pragma_ms_pointers_to_members:
4472 HandlePragmaMSPointersToMembers();
4473 continue;
4475 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
4476 #include "clang/Basic/TransformTypeTraits.def"
4477 // HACK: libstdc++ already uses '__remove_cv' as an alias template so we
4478 // work around this by expecting all transform type traits to be suffixed
4479 // with '('. They're an identifier otherwise.
4480 if (!MaybeParseTypeTransformTypeSpecifier(DS))
4481 goto ParseIdentifier;
4482 continue;
4484 case tok::kw__Atomic:
4485 // C11 6.7.2.4/4:
4486 // If the _Atomic keyword is immediately followed by a left parenthesis,
4487 // it is interpreted as a type specifier (with a type name), not as a
4488 // type qualifier.
4489 if (!getLangOpts().C11)
4490 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4492 if (NextToken().is(tok::l_paren)) {
4493 ParseAtomicSpecifier(DS);
4494 continue;
4496 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4497 getLangOpts());
4498 break;
4500 // OpenCL address space qualifiers:
4501 case tok::kw___generic:
4502 // generic address space is introduced only in OpenCL v2.0
4503 // see OpenCL C Spec v2.0 s6.5.5
4504 // OpenCL v3.0 introduces __opencl_c_generic_address_space
4505 // feature macro to indicate if generic address space is supported
4506 if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4507 DiagID = diag::err_opencl_unknown_type_specifier;
4508 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4509 isInvalid = true;
4510 break;
4512 [[fallthrough]];
4513 case tok::kw_private:
4514 // It's fine (but redundant) to check this for __generic on the
4515 // fallthrough path; we only form the __generic token in OpenCL mode.
4516 if (!getLangOpts().OpenCL)
4517 goto DoneWithDeclSpec;
4518 [[fallthrough]];
4519 case tok::kw___private:
4520 case tok::kw___global:
4521 case tok::kw___local:
4522 case tok::kw___constant:
4523 // OpenCL access qualifiers:
4524 case tok::kw___read_only:
4525 case tok::kw___write_only:
4526 case tok::kw___read_write:
4527 ParseOpenCLQualifiers(DS.getAttributes());
4528 break;
4530 case tok::kw_groupshared:
4531 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4532 ParseHLSLQualifiers(DS.getAttributes());
4533 continue;
4535 case tok::less:
4536 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4537 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4538 // but we support it.
4539 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4540 goto DoneWithDeclSpec;
4542 SourceLocation StartLoc = Tok.getLocation();
4543 SourceLocation EndLoc;
4544 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4545 if (Type.isUsable()) {
4546 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4547 PrevSpec, DiagID, Type.get(),
4548 Actions.getASTContext().getPrintingPolicy()))
4549 Diag(StartLoc, DiagID) << PrevSpec;
4551 DS.SetRangeEnd(EndLoc);
4552 } else {
4553 DS.SetTypeSpecError();
4556 // Need to support trailing type qualifiers (e.g. "id<p> const").
4557 // If a type specifier follows, it will be diagnosed elsewhere.
4558 continue;
4561 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4563 // If the specifier wasn't legal, issue a diagnostic.
4564 if (isInvalid) {
4565 assert(PrevSpec && "Method did not return previous specifier!");
4566 assert(DiagID);
4568 if (DiagID == diag::ext_duplicate_declspec ||
4569 DiagID == diag::ext_warn_duplicate_declspec ||
4570 DiagID == diag::err_duplicate_declspec)
4571 Diag(Loc, DiagID) << PrevSpec
4572 << FixItHint::CreateRemoval(
4573 SourceRange(Loc, DS.getEndLoc()));
4574 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4575 Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4576 << isStorageClass;
4577 } else
4578 Diag(Loc, DiagID) << PrevSpec;
4581 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4582 // After an error the next token can be an annotation token.
4583 ConsumeAnyToken();
4585 AttrsLastTime = false;
4589 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4590 /// semicolon.
4592 /// Note that a struct declaration refers to a declaration in a struct,
4593 /// not to the declaration of a struct.
4595 /// struct-declaration:
4596 /// [C23] attributes-specifier-seq[opt]
4597 /// specifier-qualifier-list struct-declarator-list
4598 /// [GNU] __extension__ struct-declaration
4599 /// [GNU] specifier-qualifier-list
4600 /// struct-declarator-list:
4601 /// struct-declarator
4602 /// struct-declarator-list ',' struct-declarator
4603 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4604 /// struct-declarator:
4605 /// declarator
4606 /// [GNU] declarator attributes[opt]
4607 /// declarator[opt] ':' constant-expression
4608 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4610 void Parser::ParseStructDeclaration(
4611 ParsingDeclSpec &DS,
4612 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4614 if (Tok.is(tok::kw___extension__)) {
4615 // __extension__ silences extension warnings in the subexpression.
4616 ExtensionRAIIObject O(Diags); // Use RAII to do this.
4617 ConsumeToken();
4618 return ParseStructDeclaration(DS, FieldsCallback);
4621 // Parse leading attributes.
4622 ParsedAttributes Attrs(AttrFactory);
4623 MaybeParseCXX11Attributes(Attrs);
4625 // Parse the common specifier-qualifiers-list piece.
4626 ParseSpecifierQualifierList(DS);
4628 // If there are no declarators, this is a free-standing declaration
4629 // specifier. Let the actions module cope with it.
4630 if (Tok.is(tok::semi)) {
4631 // C23 6.7.2.1p9 : "The optional attribute specifier sequence in a
4632 // member declaration appertains to each of the members declared by the
4633 // member declarator list; it shall not appear if the optional member
4634 // declarator list is omitted."
4635 ProhibitAttributes(Attrs);
4636 RecordDecl *AnonRecord = nullptr;
4637 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
4638 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
4639 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4640 DS.complete(TheDecl);
4641 return;
4644 // Read struct-declarators until we find the semicolon.
4645 bool FirstDeclarator = true;
4646 SourceLocation CommaLoc;
4647 while (true) {
4648 ParsingFieldDeclarator DeclaratorInfo(*this, DS, Attrs);
4649 DeclaratorInfo.D.setCommaLoc(CommaLoc);
4651 // Attributes are only allowed here on successive declarators.
4652 if (!FirstDeclarator) {
4653 // However, this does not apply for [[]] attributes (which could show up
4654 // before or after the __attribute__ attributes).
4655 DiagnoseAndSkipCXX11Attributes();
4656 MaybeParseGNUAttributes(DeclaratorInfo.D);
4657 DiagnoseAndSkipCXX11Attributes();
4660 /// struct-declarator: declarator
4661 /// struct-declarator: declarator[opt] ':' constant-expression
4662 if (Tok.isNot(tok::colon)) {
4663 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4664 ColonProtectionRAIIObject X(*this);
4665 ParseDeclarator(DeclaratorInfo.D);
4666 } else
4667 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4669 if (TryConsumeToken(tok::colon)) {
4670 ExprResult Res(ParseConstantExpression());
4671 if (Res.isInvalid())
4672 SkipUntil(tok::semi, StopBeforeMatch);
4673 else
4674 DeclaratorInfo.BitfieldSize = Res.get();
4677 // If attributes exist after the declarator, parse them.
4678 MaybeParseGNUAttributes(DeclaratorInfo.D);
4680 // We're done with this declarator; invoke the callback.
4681 FieldsCallback(DeclaratorInfo);
4683 // If we don't have a comma, it is either the end of the list (a ';')
4684 // or an error, bail out.
4685 if (!TryConsumeToken(tok::comma, CommaLoc))
4686 return;
4688 FirstDeclarator = false;
4692 /// ParseStructUnionBody
4693 /// struct-contents:
4694 /// struct-declaration-list
4695 /// [EXT] empty
4696 /// [GNU] "struct-declaration-list" without terminating ';'
4697 /// struct-declaration-list:
4698 /// struct-declaration
4699 /// struct-declaration-list struct-declaration
4700 /// [OBC] '@' 'defs' '(' class-name ')'
4702 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4703 DeclSpec::TST TagType, RecordDecl *TagDecl) {
4704 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4705 "parsing struct/union body");
4706 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4708 BalancedDelimiterTracker T(*this, tok::l_brace);
4709 if (T.consumeOpen())
4710 return;
4712 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4713 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4715 // While we still have something to read, read the declarations in the struct.
4716 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4717 Tok.isNot(tok::eof)) {
4718 // Each iteration of this loop reads one struct-declaration.
4720 // Check for extraneous top-level semicolon.
4721 if (Tok.is(tok::semi)) {
4722 ConsumeExtraSemi(InsideStruct, TagType);
4723 continue;
4726 // Parse _Static_assert declaration.
4727 if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
4728 SourceLocation DeclEnd;
4729 ParseStaticAssertDeclaration(DeclEnd);
4730 continue;
4733 if (Tok.is(tok::annot_pragma_pack)) {
4734 HandlePragmaPack();
4735 continue;
4738 if (Tok.is(tok::annot_pragma_align)) {
4739 HandlePragmaAlign();
4740 continue;
4743 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
4744 // Result can be ignored, because it must be always empty.
4745 AccessSpecifier AS = AS_none;
4746 ParsedAttributes Attrs(AttrFactory);
4747 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4748 continue;
4751 if (tok::isPragmaAnnotation(Tok.getKind())) {
4752 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4753 << DeclSpec::getSpecifierName(
4754 TagType, Actions.getASTContext().getPrintingPolicy());
4755 ConsumeAnnotationToken();
4756 continue;
4759 if (!Tok.is(tok::at)) {
4760 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4761 // Install the declarator into the current TagDecl.
4762 Decl *Field =
4763 Actions.ActOnField(getCurScope(), TagDecl,
4764 FD.D.getDeclSpec().getSourceRange().getBegin(),
4765 FD.D, FD.BitfieldSize);
4766 FD.complete(Field);
4769 // Parse all the comma separated declarators.
4770 ParsingDeclSpec DS(*this);
4771 ParseStructDeclaration(DS, CFieldCallback);
4772 } else { // Handle @defs
4773 ConsumeToken();
4774 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4775 Diag(Tok, diag::err_unexpected_at);
4776 SkipUntil(tok::semi);
4777 continue;
4779 ConsumeToken();
4780 ExpectAndConsume(tok::l_paren);
4781 if (!Tok.is(tok::identifier)) {
4782 Diag(Tok, diag::err_expected) << tok::identifier;
4783 SkipUntil(tok::semi);
4784 continue;
4786 SmallVector<Decl *, 16> Fields;
4787 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4788 Tok.getIdentifierInfo(), Fields);
4789 ConsumeToken();
4790 ExpectAndConsume(tok::r_paren);
4793 if (TryConsumeToken(tok::semi))
4794 continue;
4796 if (Tok.is(tok::r_brace)) {
4797 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4798 break;
4801 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4802 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4803 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4804 // If we stopped at a ';', eat it.
4805 TryConsumeToken(tok::semi);
4808 T.consumeClose();
4810 ParsedAttributes attrs(AttrFactory);
4811 // If attributes exist after struct contents, parse them.
4812 MaybeParseGNUAttributes(attrs);
4814 SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
4816 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4817 T.getOpenLocation(), T.getCloseLocation(), attrs);
4818 StructScope.Exit();
4819 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4822 /// ParseEnumSpecifier
4823 /// enum-specifier: [C99 6.7.2.2]
4824 /// 'enum' identifier[opt] '{' enumerator-list '}'
4825 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4826 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4827 /// '}' attributes[opt]
4828 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4829 /// '}'
4830 /// 'enum' identifier
4831 /// [GNU] 'enum' attributes[opt] identifier
4833 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4834 /// [C++11] enum-head '{' enumerator-list ',' '}'
4836 /// enum-head: [C++11]
4837 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4838 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4839 /// identifier enum-base[opt]
4841 /// enum-key: [C++11]
4842 /// 'enum'
4843 /// 'enum' 'class'
4844 /// 'enum' 'struct'
4846 /// enum-base: [C++11]
4847 /// ':' type-specifier-seq
4849 /// [C++] elaborated-type-specifier:
4850 /// [C++] 'enum' nested-name-specifier[opt] identifier
4852 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4853 const ParsedTemplateInfo &TemplateInfo,
4854 AccessSpecifier AS, DeclSpecContext DSC) {
4855 // Parse the tag portion of this.
4856 if (Tok.is(tok::code_completion)) {
4857 // Code completion for an enum name.
4858 cutOffParsing();
4859 Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4860 DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
4861 return;
4864 // If attributes exist after tag, parse them.
4865 ParsedAttributes attrs(AttrFactory);
4866 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4868 SourceLocation ScopedEnumKWLoc;
4869 bool IsScopedUsingClassTag = false;
4871 // In C++11, recognize 'enum class' and 'enum struct'.
4872 if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
4873 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4874 : diag::ext_scoped_enum);
4875 IsScopedUsingClassTag = Tok.is(tok::kw_class);
4876 ScopedEnumKWLoc = ConsumeToken();
4878 // Attributes are not allowed between these keywords. Diagnose,
4879 // but then just treat them like they appeared in the right place.
4880 ProhibitAttributes(attrs);
4882 // They are allowed afterwards, though.
4883 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4886 // C++11 [temp.explicit]p12:
4887 // The usual access controls do not apply to names used to specify
4888 // explicit instantiations.
4889 // We extend this to also cover explicit specializations. Note that
4890 // we don't suppress if this turns out to be an elaborated type
4891 // specifier.
4892 bool shouldDelayDiagsInTag =
4893 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4894 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4895 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4897 // Determine whether this declaration is permitted to have an enum-base.
4898 AllowDefiningTypeSpec AllowEnumSpecifier =
4899 isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus);
4900 bool CanBeOpaqueEnumDeclaration =
4901 DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
4902 bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
4903 getLangOpts().MicrosoftExt) &&
4904 (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
4905 CanBeOpaqueEnumDeclaration);
4907 CXXScopeSpec &SS = DS.getTypeSpecScope();
4908 if (getLangOpts().CPlusPlus) {
4909 // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
4910 ColonProtectionRAIIObject X(*this);
4912 CXXScopeSpec Spec;
4913 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
4914 /*ObjectHasErrors=*/false,
4915 /*EnteringContext=*/true))
4916 return;
4918 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4919 Diag(Tok, diag::err_expected) << tok::identifier;
4920 DS.SetTypeSpecError();
4921 if (Tok.isNot(tok::l_brace)) {
4922 // Has no name and is not a definition.
4923 // Skip the rest of this declarator, up until the comma or semicolon.
4924 SkipUntil(tok::comma, StopAtSemi);
4925 return;
4929 SS = Spec;
4932 // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
4933 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4934 Tok.isNot(tok::colon)) {
4935 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4937 DS.SetTypeSpecError();
4938 // Skip the rest of this declarator, up until the comma or semicolon.
4939 SkipUntil(tok::comma, StopAtSemi);
4940 return;
4943 // If an identifier is present, consume and remember it.
4944 IdentifierInfo *Name = nullptr;
4945 SourceLocation NameLoc;
4946 if (Tok.is(tok::identifier)) {
4947 Name = Tok.getIdentifierInfo();
4948 NameLoc = ConsumeToken();
4951 if (!Name && ScopedEnumKWLoc.isValid()) {
4952 // C++0x 7.2p2: The optional identifier shall not be omitted in the
4953 // declaration of a scoped enumeration.
4954 Diag(Tok, diag::err_scoped_enum_missing_identifier);
4955 ScopedEnumKWLoc = SourceLocation();
4956 IsScopedUsingClassTag = false;
4959 // Okay, end the suppression area. We'll decide whether to emit the
4960 // diagnostics in a second.
4961 if (shouldDelayDiagsInTag)
4962 diagsFromTag.done();
4964 TypeResult BaseType;
4965 SourceRange BaseRange;
4967 bool CanBeBitfield =
4968 getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
4970 // Parse the fixed underlying type.
4971 if (Tok.is(tok::colon)) {
4972 // This might be an enum-base or part of some unrelated enclosing context.
4974 // 'enum E : base' is permitted in two circumstances:
4976 // 1) As a defining-type-specifier, when followed by '{'.
4977 // 2) As the sole constituent of a complete declaration -- when DS is empty
4978 // and the next token is ';'.
4980 // The restriction to defining-type-specifiers is important to allow parsing
4981 // a ? new enum E : int{}
4982 // _Generic(a, enum E : int{})
4983 // properly.
4985 // One additional consideration applies:
4987 // C++ [dcl.enum]p1:
4988 // A ':' following "enum nested-name-specifier[opt] identifier" within
4989 // the decl-specifier-seq of a member-declaration is parsed as part of
4990 // an enum-base.
4992 // Other language modes supporting enumerations with fixed underlying types
4993 // do not have clear rules on this, so we disambiguate to determine whether
4994 // the tokens form a bit-field width or an enum-base.
4996 if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
4997 // Outside C++11, do not interpret the tokens as an enum-base if they do
4998 // not make sense as one. In C++11, it's an error if this happens.
4999 if (getLangOpts().CPlusPlus11)
5000 Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
5001 } else if (CanHaveEnumBase || !ColonIsSacred) {
5002 SourceLocation ColonLoc = ConsumeToken();
5004 // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
5005 // because under -fms-extensions,
5006 // enum E : int *p;
5007 // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
5008 DeclSpec DS(AttrFactory);
5009 // enum-base is not assumed to be a type and therefore requires the
5010 // typename keyword [p0634r3].
5011 ParseSpecifierQualifierList(DS, ImplicitTypenameContext::No, AS,
5012 DeclSpecContext::DSC_type_specifier);
5013 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
5014 DeclaratorContext::TypeName);
5015 BaseType = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
5017 BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
5019 if (!getLangOpts().ObjC && !getLangOpts().C23) {
5020 if (getLangOpts().CPlusPlus11)
5021 Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
5022 << BaseRange;
5023 else if (getLangOpts().CPlusPlus)
5024 Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
5025 << BaseRange;
5026 else if (getLangOpts().MicrosoftExt)
5027 Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
5028 << BaseRange;
5029 else
5030 Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
5031 << BaseRange;
5036 // There are four options here. If we have 'friend enum foo;' then this is a
5037 // friend declaration, and cannot have an accompanying definition. If we have
5038 // 'enum foo;', then this is a forward declaration. If we have
5039 // 'enum foo {...' then this is a definition. Otherwise we have something
5040 // like 'enum foo xyz', a reference.
5042 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
5043 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
5044 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
5046 Sema::TagUseKind TUK;
5047 if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
5048 TUK = Sema::TUK_Reference;
5049 else if (Tok.is(tok::l_brace)) {
5050 if (DS.isFriendSpecified()) {
5051 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
5052 << SourceRange(DS.getFriendSpecLoc());
5053 ConsumeBrace();
5054 SkipUntil(tok::r_brace, StopAtSemi);
5055 // Discard any other definition-only pieces.
5056 attrs.clear();
5057 ScopedEnumKWLoc = SourceLocation();
5058 IsScopedUsingClassTag = false;
5059 BaseType = TypeResult();
5060 TUK = Sema::TUK_Friend;
5061 } else {
5062 TUK = Sema::TUK_Definition;
5064 } else if (!isTypeSpecifier(DSC) &&
5065 (Tok.is(tok::semi) ||
5066 (Tok.isAtStartOfLine() &&
5067 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
5068 // An opaque-enum-declaration is required to be standalone (no preceding or
5069 // following tokens in the declaration). Sema enforces this separately by
5070 // diagnosing anything else in the DeclSpec.
5071 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
5072 if (Tok.isNot(tok::semi)) {
5073 // A semicolon was missing after this declaration. Diagnose and recover.
5074 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5075 PP.EnterToken(Tok, /*IsReinject=*/true);
5076 Tok.setKind(tok::semi);
5078 } else {
5079 TUK = Sema::TUK_Reference;
5082 bool IsElaboratedTypeSpecifier =
5083 TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend;
5085 // If this is an elaborated type specifier nested in a larger declaration,
5086 // and we delayed diagnostics before, just merge them into the current pool.
5087 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
5088 diagsFromTag.redelay();
5091 MultiTemplateParamsArg TParams;
5092 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
5093 TUK != Sema::TUK_Reference) {
5094 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
5095 // Skip the rest of this declarator, up until the comma or semicolon.
5096 Diag(Tok, diag::err_enum_template);
5097 SkipUntil(tok::comma, StopAtSemi);
5098 return;
5101 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
5102 // Enumerations can't be explicitly instantiated.
5103 DS.SetTypeSpecError();
5104 Diag(StartLoc, diag::err_explicit_instantiation_enum);
5105 return;
5108 assert(TemplateInfo.TemplateParams && "no template parameters");
5109 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
5110 TemplateInfo.TemplateParams->size());
5111 SS.setTemplateParamLists(TParams);
5114 if (!Name && TUK != Sema::TUK_Definition) {
5115 Diag(Tok, diag::err_enumerator_unnamed_no_def);
5117 DS.SetTypeSpecError();
5118 // Skip the rest of this declarator, up until the comma or semicolon.
5119 SkipUntil(tok::comma, StopAtSemi);
5120 return;
5123 // An elaborated-type-specifier has a much more constrained grammar:
5125 // 'enum' nested-name-specifier[opt] identifier
5127 // If we parsed any other bits, reject them now.
5129 // MSVC and (for now at least) Objective-C permit a full enum-specifier
5130 // or opaque-enum-declaration anywhere.
5131 if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
5132 !getLangOpts().ObjC) {
5133 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
5134 diag::err_keyword_not_allowed,
5135 /*DiagnoseEmptyAttrs=*/true);
5136 if (BaseType.isUsable())
5137 Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
5138 << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
5139 else if (ScopedEnumKWLoc.isValid())
5140 Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
5141 << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
5144 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
5146 Sema::SkipBodyInfo SkipBody;
5147 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
5148 NextToken().is(tok::identifier))
5149 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
5150 NextToken().getIdentifierInfo(),
5151 NextToken().getLocation());
5153 bool Owned = false;
5154 bool IsDependent = false;
5155 const char *PrevSpec = nullptr;
5156 unsigned DiagID;
5157 Decl *TagDecl =
5158 Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS,
5159 Name, NameLoc, attrs, AS, DS.getModulePrivateSpecLoc(),
5160 TParams, Owned, IsDependent, ScopedEnumKWLoc,
5161 IsScopedUsingClassTag,
5162 BaseType, DSC == DeclSpecContext::DSC_type_specifier,
5163 DSC == DeclSpecContext::DSC_template_param ||
5164 DSC == DeclSpecContext::DSC_template_type_arg,
5165 OffsetOfState, &SkipBody).get();
5167 if (SkipBody.ShouldSkip) {
5168 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
5170 BalancedDelimiterTracker T(*this, tok::l_brace);
5171 T.consumeOpen();
5172 T.skipToEnd();
5174 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5175 NameLoc.isValid() ? NameLoc : StartLoc,
5176 PrevSpec, DiagID, TagDecl, Owned,
5177 Actions.getASTContext().getPrintingPolicy()))
5178 Diag(StartLoc, DiagID) << PrevSpec;
5179 return;
5182 if (IsDependent) {
5183 // This enum has a dependent nested-name-specifier. Handle it as a
5184 // dependent tag.
5185 if (!Name) {
5186 DS.SetTypeSpecError();
5187 Diag(Tok, diag::err_expected_type_name_after_typename);
5188 return;
5191 TypeResult Type = Actions.ActOnDependentTag(
5192 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
5193 if (Type.isInvalid()) {
5194 DS.SetTypeSpecError();
5195 return;
5198 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
5199 NameLoc.isValid() ? NameLoc : StartLoc,
5200 PrevSpec, DiagID, Type.get(),
5201 Actions.getASTContext().getPrintingPolicy()))
5202 Diag(StartLoc, DiagID) << PrevSpec;
5204 return;
5207 if (!TagDecl) {
5208 // The action failed to produce an enumeration tag. If this is a
5209 // definition, consume the entire definition.
5210 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
5211 ConsumeBrace();
5212 SkipUntil(tok::r_brace, StopAtSemi);
5215 DS.SetTypeSpecError();
5216 return;
5219 if (Tok.is(tok::l_brace) && TUK == Sema::TUK_Definition) {
5220 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
5221 ParseEnumBody(StartLoc, D);
5222 if (SkipBody.CheckSameAsPrevious &&
5223 !Actions.ActOnDuplicateDefinition(TagDecl, SkipBody)) {
5224 DS.SetTypeSpecError();
5225 return;
5229 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5230 NameLoc.isValid() ? NameLoc : StartLoc,
5231 PrevSpec, DiagID, TagDecl, Owned,
5232 Actions.getASTContext().getPrintingPolicy()))
5233 Diag(StartLoc, DiagID) << PrevSpec;
5236 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
5237 /// enumerator-list:
5238 /// enumerator
5239 /// enumerator-list ',' enumerator
5240 /// enumerator:
5241 /// enumeration-constant attributes[opt]
5242 /// enumeration-constant attributes[opt] '=' constant-expression
5243 /// enumeration-constant:
5244 /// identifier
5246 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
5247 // Enter the scope of the enum body and start the definition.
5248 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
5249 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
5251 BalancedDelimiterTracker T(*this, tok::l_brace);
5252 T.consumeOpen();
5254 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
5255 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
5256 Diag(Tok, diag::err_empty_enum);
5258 SmallVector<Decl *, 32> EnumConstantDecls;
5259 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
5261 Decl *LastEnumConstDecl = nullptr;
5263 // Parse the enumerator-list.
5264 while (Tok.isNot(tok::r_brace)) {
5265 // Parse enumerator. If failed, try skipping till the start of the next
5266 // enumerator definition.
5267 if (Tok.isNot(tok::identifier)) {
5268 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
5269 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
5270 TryConsumeToken(tok::comma))
5271 continue;
5272 break;
5274 IdentifierInfo *Ident = Tok.getIdentifierInfo();
5275 SourceLocation IdentLoc = ConsumeToken();
5277 // If attributes exist after the enumerator, parse them.
5278 ParsedAttributes attrs(AttrFactory);
5279 MaybeParseGNUAttributes(attrs);
5280 if (isAllowedCXX11AttributeSpecifier()) {
5281 if (getLangOpts().CPlusPlus)
5282 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
5283 ? diag::warn_cxx14_compat_ns_enum_attribute
5284 : diag::ext_ns_enum_attribute)
5285 << 1 /*enumerator*/;
5286 ParseCXX11Attributes(attrs);
5289 SourceLocation EqualLoc;
5290 ExprResult AssignedVal;
5291 EnumAvailabilityDiags.emplace_back(*this);
5293 EnterExpressionEvaluationContext ConstantEvaluated(
5294 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5295 if (TryConsumeToken(tok::equal, EqualLoc)) {
5296 AssignedVal = ParseConstantExpressionInExprEvalContext();
5297 if (AssignedVal.isInvalid())
5298 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
5301 // Install the enumerator constant into EnumDecl.
5302 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
5303 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
5304 EqualLoc, AssignedVal.get());
5305 EnumAvailabilityDiags.back().done();
5307 EnumConstantDecls.push_back(EnumConstDecl);
5308 LastEnumConstDecl = EnumConstDecl;
5310 if (Tok.is(tok::identifier)) {
5311 // We're missing a comma between enumerators.
5312 SourceLocation Loc = getEndOfPreviousToken();
5313 Diag(Loc, diag::err_enumerator_list_missing_comma)
5314 << FixItHint::CreateInsertion(Loc, ", ");
5315 continue;
5318 // Emumerator definition must be finished, only comma or r_brace are
5319 // allowed here.
5320 SourceLocation CommaLoc;
5321 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
5322 if (EqualLoc.isValid())
5323 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
5324 << tok::comma;
5325 else
5326 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
5327 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
5328 if (TryConsumeToken(tok::comma, CommaLoc))
5329 continue;
5330 } else {
5331 break;
5335 // If comma is followed by r_brace, emit appropriate warning.
5336 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
5337 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
5338 Diag(CommaLoc, getLangOpts().CPlusPlus ?
5339 diag::ext_enumerator_list_comma_cxx :
5340 diag::ext_enumerator_list_comma_c)
5341 << FixItHint::CreateRemoval(CommaLoc);
5342 else if (getLangOpts().CPlusPlus11)
5343 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
5344 << FixItHint::CreateRemoval(CommaLoc);
5345 break;
5349 // Eat the }.
5350 T.consumeClose();
5352 // If attributes exist after the identifier list, parse them.
5353 ParsedAttributes attrs(AttrFactory);
5354 MaybeParseGNUAttributes(attrs);
5356 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
5357 getCurScope(), attrs);
5359 // Now handle enum constant availability diagnostics.
5360 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
5361 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
5362 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
5363 EnumAvailabilityDiags[i].redelay();
5364 PD.complete(EnumConstantDecls[i]);
5367 EnumScope.Exit();
5368 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
5370 // The next token must be valid after an enum definition. If not, a ';'
5371 // was probably forgotten.
5372 bool CanBeBitfield = getCurScope()->isClassScope();
5373 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
5374 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5375 // Push this token back into the preprocessor and change our current token
5376 // to ';' so that the rest of the code recovers as though there were an
5377 // ';' after the definition.
5378 PP.EnterToken(Tok, /*IsReinject=*/true);
5379 Tok.setKind(tok::semi);
5383 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
5384 /// is definitely a type-specifier. Return false if it isn't part of a type
5385 /// specifier or if we're not sure.
5386 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
5387 switch (Tok.getKind()) {
5388 default: return false;
5389 // type-specifiers
5390 case tok::kw_short:
5391 case tok::kw_long:
5392 case tok::kw___int64:
5393 case tok::kw___int128:
5394 case tok::kw_signed:
5395 case tok::kw_unsigned:
5396 case tok::kw__Complex:
5397 case tok::kw__Imaginary:
5398 case tok::kw_void:
5399 case tok::kw_char:
5400 case tok::kw_wchar_t:
5401 case tok::kw_char8_t:
5402 case tok::kw_char16_t:
5403 case tok::kw_char32_t:
5404 case tok::kw_int:
5405 case tok::kw__ExtInt:
5406 case tok::kw__BitInt:
5407 case tok::kw___bf16:
5408 case tok::kw_half:
5409 case tok::kw_float:
5410 case tok::kw_double:
5411 case tok::kw__Accum:
5412 case tok::kw__Fract:
5413 case tok::kw__Float16:
5414 case tok::kw___float128:
5415 case tok::kw___ibm128:
5416 case tok::kw_bool:
5417 case tok::kw__Bool:
5418 case tok::kw__Decimal32:
5419 case tok::kw__Decimal64:
5420 case tok::kw__Decimal128:
5421 case tok::kw___vector:
5422 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5423 #include "clang/Basic/OpenCLImageTypes.def"
5425 // struct-or-union-specifier (C99) or class-specifier (C++)
5426 case tok::kw_class:
5427 case tok::kw_struct:
5428 case tok::kw___interface:
5429 case tok::kw_union:
5430 // enum-specifier
5431 case tok::kw_enum:
5433 // typedef-name
5434 case tok::annot_typename:
5435 return true;
5439 /// isTypeSpecifierQualifier - Return true if the current token could be the
5440 /// start of a specifier-qualifier-list.
5441 bool Parser::isTypeSpecifierQualifier() {
5442 switch (Tok.getKind()) {
5443 default: return false;
5445 case tok::identifier: // foo::bar
5446 if (TryAltiVecVectorToken())
5447 return true;
5448 [[fallthrough]];
5449 case tok::kw_typename: // typename T::type
5450 // Annotate typenames and C++ scope specifiers. If we get one, just
5451 // recurse to handle whatever we get.
5452 if (TryAnnotateTypeOrScopeToken())
5453 return true;
5454 if (Tok.is(tok::identifier))
5455 return false;
5456 return isTypeSpecifierQualifier();
5458 case tok::coloncolon: // ::foo::bar
5459 if (NextToken().is(tok::kw_new) || // ::new
5460 NextToken().is(tok::kw_delete)) // ::delete
5461 return false;
5463 if (TryAnnotateTypeOrScopeToken())
5464 return true;
5465 return isTypeSpecifierQualifier();
5467 // GNU attributes support.
5468 case tok::kw___attribute:
5469 // C23/GNU typeof support.
5470 case tok::kw_typeof:
5471 case tok::kw_typeof_unqual:
5473 // type-specifiers
5474 case tok::kw_short:
5475 case tok::kw_long:
5476 case tok::kw___int64:
5477 case tok::kw___int128:
5478 case tok::kw_signed:
5479 case tok::kw_unsigned:
5480 case tok::kw__Complex:
5481 case tok::kw__Imaginary:
5482 case tok::kw_void:
5483 case tok::kw_char:
5484 case tok::kw_wchar_t:
5485 case tok::kw_char8_t:
5486 case tok::kw_char16_t:
5487 case tok::kw_char32_t:
5488 case tok::kw_int:
5489 case tok::kw__ExtInt:
5490 case tok::kw__BitInt:
5491 case tok::kw_half:
5492 case tok::kw___bf16:
5493 case tok::kw_float:
5494 case tok::kw_double:
5495 case tok::kw__Accum:
5496 case tok::kw__Fract:
5497 case tok::kw__Float16:
5498 case tok::kw___float128:
5499 case tok::kw___ibm128:
5500 case tok::kw_bool:
5501 case tok::kw__Bool:
5502 case tok::kw__Decimal32:
5503 case tok::kw__Decimal64:
5504 case tok::kw__Decimal128:
5505 case tok::kw___vector:
5506 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5507 #include "clang/Basic/OpenCLImageTypes.def"
5509 // struct-or-union-specifier (C99) or class-specifier (C++)
5510 case tok::kw_class:
5511 case tok::kw_struct:
5512 case tok::kw___interface:
5513 case tok::kw_union:
5514 // enum-specifier
5515 case tok::kw_enum:
5517 // type-qualifier
5518 case tok::kw_const:
5519 case tok::kw_volatile:
5520 case tok::kw_restrict:
5521 case tok::kw__Sat:
5523 // Debugger support.
5524 case tok::kw___unknown_anytype:
5526 // typedef-name
5527 case tok::annot_typename:
5528 return true;
5530 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5531 case tok::less:
5532 return getLangOpts().ObjC;
5534 case tok::kw___cdecl:
5535 case tok::kw___stdcall:
5536 case tok::kw___fastcall:
5537 case tok::kw___thiscall:
5538 case tok::kw___regcall:
5539 case tok::kw___vectorcall:
5540 case tok::kw___w64:
5541 case tok::kw___ptr64:
5542 case tok::kw___ptr32:
5543 case tok::kw___pascal:
5544 case tok::kw___unaligned:
5546 case tok::kw__Nonnull:
5547 case tok::kw__Nullable:
5548 case tok::kw__Nullable_result:
5549 case tok::kw__Null_unspecified:
5551 case tok::kw___kindof:
5553 case tok::kw___private:
5554 case tok::kw___local:
5555 case tok::kw___global:
5556 case tok::kw___constant:
5557 case tok::kw___generic:
5558 case tok::kw___read_only:
5559 case tok::kw___read_write:
5560 case tok::kw___write_only:
5561 case tok::kw___funcref:
5562 case tok::kw_groupshared:
5563 return true;
5565 case tok::kw_private:
5566 return getLangOpts().OpenCL;
5568 // C11 _Atomic
5569 case tok::kw__Atomic:
5570 return true;
5574 Parser::DeclGroupPtrTy Parser::ParseTopLevelStmtDecl() {
5575 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode");
5577 // Parse a top-level-stmt.
5578 Parser::StmtVector Stmts;
5579 ParsedStmtContext SubStmtCtx = ParsedStmtContext();
5580 Actions.PushFunctionScope();
5581 StmtResult R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
5582 Actions.PopFunctionScopeInfo();
5583 if (!R.isUsable())
5584 return nullptr;
5586 SmallVector<Decl *, 2> DeclsInGroup;
5587 DeclsInGroup.push_back(Actions.ActOnTopLevelStmtDecl(R.get()));
5589 if (Tok.is(tok::annot_repl_input_end) &&
5590 Tok.getAnnotationValue() != nullptr) {
5591 ConsumeAnnotationToken();
5592 cast<TopLevelStmtDecl>(DeclsInGroup.back())->setSemiMissing();
5595 // Currently happens for things like -fms-extensions and use `__if_exists`.
5596 for (Stmt *S : Stmts)
5597 DeclsInGroup.push_back(Actions.ActOnTopLevelStmtDecl(S));
5599 return Actions.BuildDeclaratorGroup(DeclsInGroup);
5602 /// isDeclarationSpecifier() - Return true if the current token is part of a
5603 /// declaration specifier.
5605 /// \param AllowImplicitTypename whether this is a context where T::type [T
5606 /// dependent] can appear.
5607 /// \param DisambiguatingWithExpression True to indicate that the purpose of
5608 /// this check is to disambiguate between an expression and a declaration.
5609 bool Parser::isDeclarationSpecifier(
5610 ImplicitTypenameContext AllowImplicitTypename,
5611 bool DisambiguatingWithExpression) {
5612 switch (Tok.getKind()) {
5613 default: return false;
5615 // OpenCL 2.0 and later define this keyword.
5616 case tok::kw_pipe:
5617 return getLangOpts().OpenCL &&
5618 getLangOpts().getOpenCLCompatibleVersion() >= 200;
5620 case tok::identifier: // foo::bar
5621 // Unfortunate hack to support "Class.factoryMethod" notation.
5622 if (getLangOpts().ObjC && NextToken().is(tok::period))
5623 return false;
5624 if (TryAltiVecVectorToken())
5625 return true;
5626 [[fallthrough]];
5627 case tok::kw_decltype: // decltype(T())::type
5628 case tok::kw_typename: // typename T::type
5629 // Annotate typenames and C++ scope specifiers. If we get one, just
5630 // recurse to handle whatever we get.
5631 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
5632 return true;
5633 if (TryAnnotateTypeConstraint())
5634 return true;
5635 if (Tok.is(tok::identifier))
5636 return false;
5638 // If we're in Objective-C and we have an Objective-C class type followed
5639 // by an identifier and then either ':' or ']', in a place where an
5640 // expression is permitted, then this is probably a class message send
5641 // missing the initial '['. In this case, we won't consider this to be
5642 // the start of a declaration.
5643 if (DisambiguatingWithExpression &&
5644 isStartOfObjCClassMessageMissingOpenBracket())
5645 return false;
5647 return isDeclarationSpecifier(AllowImplicitTypename);
5649 case tok::coloncolon: // ::foo::bar
5650 if (!getLangOpts().CPlusPlus)
5651 return false;
5652 if (NextToken().is(tok::kw_new) || // ::new
5653 NextToken().is(tok::kw_delete)) // ::delete
5654 return false;
5656 // Annotate typenames and C++ scope specifiers. If we get one, just
5657 // recurse to handle whatever we get.
5658 if (TryAnnotateTypeOrScopeToken())
5659 return true;
5660 return isDeclarationSpecifier(ImplicitTypenameContext::No);
5662 // storage-class-specifier
5663 case tok::kw_typedef:
5664 case tok::kw_extern:
5665 case tok::kw___private_extern__:
5666 case tok::kw_static:
5667 case tok::kw_auto:
5668 case tok::kw___auto_type:
5669 case tok::kw_register:
5670 case tok::kw___thread:
5671 case tok::kw_thread_local:
5672 case tok::kw__Thread_local:
5674 // Modules
5675 case tok::kw___module_private__:
5677 // Debugger support
5678 case tok::kw___unknown_anytype:
5680 // type-specifiers
5681 case tok::kw_short:
5682 case tok::kw_long:
5683 case tok::kw___int64:
5684 case tok::kw___int128:
5685 case tok::kw_signed:
5686 case tok::kw_unsigned:
5687 case tok::kw__Complex:
5688 case tok::kw__Imaginary:
5689 case tok::kw_void:
5690 case tok::kw_char:
5691 case tok::kw_wchar_t:
5692 case tok::kw_char8_t:
5693 case tok::kw_char16_t:
5694 case tok::kw_char32_t:
5696 case tok::kw_int:
5697 case tok::kw__ExtInt:
5698 case tok::kw__BitInt:
5699 case tok::kw_half:
5700 case tok::kw___bf16:
5701 case tok::kw_float:
5702 case tok::kw_double:
5703 case tok::kw__Accum:
5704 case tok::kw__Fract:
5705 case tok::kw__Float16:
5706 case tok::kw___float128:
5707 case tok::kw___ibm128:
5708 case tok::kw_bool:
5709 case tok::kw__Bool:
5710 case tok::kw__Decimal32:
5711 case tok::kw__Decimal64:
5712 case tok::kw__Decimal128:
5713 case tok::kw___vector:
5715 // struct-or-union-specifier (C99) or class-specifier (C++)
5716 case tok::kw_class:
5717 case tok::kw_struct:
5718 case tok::kw_union:
5719 case tok::kw___interface:
5720 // enum-specifier
5721 case tok::kw_enum:
5723 // type-qualifier
5724 case tok::kw_const:
5725 case tok::kw_volatile:
5726 case tok::kw_restrict:
5727 case tok::kw__Sat:
5729 // function-specifier
5730 case tok::kw_inline:
5731 case tok::kw_virtual:
5732 case tok::kw_explicit:
5733 case tok::kw__Noreturn:
5735 // alignment-specifier
5736 case tok::kw__Alignas:
5738 // friend keyword.
5739 case tok::kw_friend:
5741 // static_assert-declaration
5742 case tok::kw_static_assert:
5743 case tok::kw__Static_assert:
5745 // C23/GNU typeof support.
5746 case tok::kw_typeof:
5747 case tok::kw_typeof_unqual:
5749 // GNU attributes.
5750 case tok::kw___attribute:
5752 // C++11 decltype and constexpr.
5753 case tok::annot_decltype:
5754 case tok::kw_constexpr:
5756 // C++20 consteval and constinit.
5757 case tok::kw_consteval:
5758 case tok::kw_constinit:
5760 // C11 _Atomic
5761 case tok::kw__Atomic:
5762 return true;
5764 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5765 case tok::less:
5766 return getLangOpts().ObjC;
5768 // typedef-name
5769 case tok::annot_typename:
5770 return !DisambiguatingWithExpression ||
5771 !isStartOfObjCClassMessageMissingOpenBracket();
5773 // placeholder-type-specifier
5774 case tok::annot_template_id: {
5775 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
5776 if (TemplateId->hasInvalidName())
5777 return true;
5778 // FIXME: What about type templates that have only been annotated as
5779 // annot_template_id, not as annot_typename?
5780 return isTypeConstraintAnnotation() &&
5781 (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
5784 case tok::annot_cxxscope: {
5785 TemplateIdAnnotation *TemplateId =
5786 NextToken().is(tok::annot_template_id)
5787 ? takeTemplateIdAnnotation(NextToken())
5788 : nullptr;
5789 if (TemplateId && TemplateId->hasInvalidName())
5790 return true;
5791 // FIXME: What about type templates that have only been annotated as
5792 // annot_template_id, not as annot_typename?
5793 if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
5794 return true;
5795 return isTypeConstraintAnnotation() &&
5796 GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
5799 case tok::kw___declspec:
5800 case tok::kw___cdecl:
5801 case tok::kw___stdcall:
5802 case tok::kw___fastcall:
5803 case tok::kw___thiscall:
5804 case tok::kw___regcall:
5805 case tok::kw___vectorcall:
5806 case tok::kw___w64:
5807 case tok::kw___sptr:
5808 case tok::kw___uptr:
5809 case tok::kw___ptr64:
5810 case tok::kw___ptr32:
5811 case tok::kw___forceinline:
5812 case tok::kw___pascal:
5813 case tok::kw___unaligned:
5815 case tok::kw__Nonnull:
5816 case tok::kw__Nullable:
5817 case tok::kw__Nullable_result:
5818 case tok::kw__Null_unspecified:
5820 case tok::kw___kindof:
5822 case tok::kw___private:
5823 case tok::kw___local:
5824 case tok::kw___global:
5825 case tok::kw___constant:
5826 case tok::kw___generic:
5827 case tok::kw___read_only:
5828 case tok::kw___read_write:
5829 case tok::kw___write_only:
5830 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5831 #include "clang/Basic/OpenCLImageTypes.def"
5833 case tok::kw___funcref:
5834 case tok::kw_groupshared:
5835 return true;
5837 case tok::kw_private:
5838 return getLangOpts().OpenCL;
5842 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide,
5843 DeclSpec::FriendSpecified IsFriend,
5844 const ParsedTemplateInfo *TemplateInfo) {
5845 RevertingTentativeParsingAction TPA(*this);
5846 // Parse the C++ scope specifier.
5847 CXXScopeSpec SS;
5848 if (TemplateInfo && TemplateInfo->TemplateParams)
5849 SS.setTemplateParamLists(*TemplateInfo->TemplateParams);
5851 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
5852 /*ObjectHasErrors=*/false,
5853 /*EnteringContext=*/true)) {
5854 return false;
5857 // Parse the constructor name.
5858 if (Tok.is(tok::identifier)) {
5859 // We already know that we have a constructor name; just consume
5860 // the token.
5861 ConsumeToken();
5862 } else if (Tok.is(tok::annot_template_id)) {
5863 ConsumeAnnotationToken();
5864 } else {
5865 return false;
5868 // There may be attributes here, appertaining to the constructor name or type
5869 // we just stepped past.
5870 SkipCXX11Attributes();
5872 // Current class name must be followed by a left parenthesis.
5873 if (Tok.isNot(tok::l_paren)) {
5874 return false;
5876 ConsumeParen();
5878 // A right parenthesis, or ellipsis followed by a right parenthesis signals
5879 // that we have a constructor.
5880 if (Tok.is(tok::r_paren) ||
5881 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5882 return true;
5885 // A C++11 attribute here signals that we have a constructor, and is an
5886 // attribute on the first constructor parameter.
5887 if (getLangOpts().CPlusPlus11 &&
5888 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5889 /*OuterMightBeMessageSend*/ true)) {
5890 return true;
5893 // If we need to, enter the specified scope.
5894 DeclaratorScopeObj DeclScopeObj(*this, SS);
5895 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5896 DeclScopeObj.EnterDeclaratorScope();
5898 // Optionally skip Microsoft attributes.
5899 ParsedAttributes Attrs(AttrFactory);
5900 MaybeParseMicrosoftAttributes(Attrs);
5902 // Check whether the next token(s) are part of a declaration
5903 // specifier, in which case we have the start of a parameter and,
5904 // therefore, we know that this is a constructor.
5905 // Due to an ambiguity with implicit typename, the above is not enough.
5906 // Additionally, check to see if we are a friend.
5907 // If we parsed a scope specifier as well as friend,
5908 // we might be parsing a friend constructor.
5909 bool IsConstructor = false;
5910 ImplicitTypenameContext ITC = IsFriend && !SS.isSet()
5911 ? ImplicitTypenameContext::No
5912 : ImplicitTypenameContext::Yes;
5913 // Constructors cannot have this parameters, but we support that scenario here
5914 // to improve diagnostic.
5915 if (Tok.is(tok::kw_this)) {
5916 ConsumeToken();
5917 return isDeclarationSpecifier(ITC);
5920 if (isDeclarationSpecifier(ITC))
5921 IsConstructor = true;
5922 else if (Tok.is(tok::identifier) ||
5923 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5924 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5925 // This might be a parenthesized member name, but is more likely to
5926 // be a constructor declaration with an invalid argument type. Keep
5927 // looking.
5928 if (Tok.is(tok::annot_cxxscope))
5929 ConsumeAnnotationToken();
5930 ConsumeToken();
5932 // If this is not a constructor, we must be parsing a declarator,
5933 // which must have one of the following syntactic forms (see the
5934 // grammar extract at the start of ParseDirectDeclarator):
5935 switch (Tok.getKind()) {
5936 case tok::l_paren:
5937 // C(X ( int));
5938 case tok::l_square:
5939 // C(X [ 5]);
5940 // C(X [ [attribute]]);
5941 case tok::coloncolon:
5942 // C(X :: Y);
5943 // C(X :: *p);
5944 // Assume this isn't a constructor, rather than assuming it's a
5945 // constructor with an unnamed parameter of an ill-formed type.
5946 break;
5948 case tok::r_paren:
5949 // C(X )
5951 // Skip past the right-paren and any following attributes to get to
5952 // the function body or trailing-return-type.
5953 ConsumeParen();
5954 SkipCXX11Attributes();
5956 if (DeductionGuide) {
5957 // C(X) -> ... is a deduction guide.
5958 IsConstructor = Tok.is(tok::arrow);
5959 break;
5961 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5962 // Assume these were meant to be constructors:
5963 // C(X) : (the name of a bit-field cannot be parenthesized).
5964 // C(X) try (this is otherwise ill-formed).
5965 IsConstructor = true;
5967 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5968 // If we have a constructor name within the class definition,
5969 // assume these were meant to be constructors:
5970 // C(X) {
5971 // C(X) ;
5972 // ... because otherwise we would be declaring a non-static data
5973 // member that is ill-formed because it's of the same type as its
5974 // surrounding class.
5976 // FIXME: We can actually do this whether or not the name is qualified,
5977 // because if it is qualified in this context it must be being used as
5978 // a constructor name.
5979 // currently, so we're somewhat conservative here.
5980 IsConstructor = IsUnqualified;
5982 break;
5984 default:
5985 IsConstructor = true;
5986 break;
5989 return IsConstructor;
5992 /// ParseTypeQualifierListOpt
5993 /// type-qualifier-list: [C99 6.7.5]
5994 /// type-qualifier
5995 /// [vendor] attributes
5996 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5997 /// type-qualifier-list type-qualifier
5998 /// [vendor] type-qualifier-list attributes
5999 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
6000 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
6001 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
6002 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
6003 /// AttrRequirements bitmask values.
6004 void Parser::ParseTypeQualifierListOpt(
6005 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
6006 bool IdentifierRequired,
6007 std::optional<llvm::function_ref<void()>> CodeCompletionHandler) {
6008 if ((AttrReqs & AR_CXX11AttributesParsed) &&
6009 isAllowedCXX11AttributeSpecifier()) {
6010 ParsedAttributes Attrs(AttrFactory);
6011 ParseCXX11Attributes(Attrs);
6012 DS.takeAttributesFrom(Attrs);
6015 SourceLocation EndLoc;
6017 while (true) {
6018 bool isInvalid = false;
6019 const char *PrevSpec = nullptr;
6020 unsigned DiagID = 0;
6021 SourceLocation Loc = Tok.getLocation();
6023 switch (Tok.getKind()) {
6024 case tok::code_completion:
6025 cutOffParsing();
6026 if (CodeCompletionHandler)
6027 (*CodeCompletionHandler)();
6028 else
6029 Actions.CodeCompleteTypeQualifiers(DS);
6030 return;
6032 case tok::kw_const:
6033 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
6034 getLangOpts());
6035 break;
6036 case tok::kw_volatile:
6037 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
6038 getLangOpts());
6039 break;
6040 case tok::kw_restrict:
6041 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
6042 getLangOpts());
6043 break;
6044 case tok::kw__Atomic:
6045 if (!AtomicAllowed)
6046 goto DoneWithTypeQuals;
6047 if (!getLangOpts().C11)
6048 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
6049 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
6050 getLangOpts());
6051 break;
6053 // OpenCL qualifiers:
6054 case tok::kw_private:
6055 if (!getLangOpts().OpenCL)
6056 goto DoneWithTypeQuals;
6057 [[fallthrough]];
6058 case tok::kw___private:
6059 case tok::kw___global:
6060 case tok::kw___local:
6061 case tok::kw___constant:
6062 case tok::kw___generic:
6063 case tok::kw___read_only:
6064 case tok::kw___write_only:
6065 case tok::kw___read_write:
6066 ParseOpenCLQualifiers(DS.getAttributes());
6067 break;
6069 case tok::kw_groupshared:
6070 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
6071 ParseHLSLQualifiers(DS.getAttributes());
6072 continue;
6074 case tok::kw___unaligned:
6075 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
6076 getLangOpts());
6077 break;
6078 case tok::kw___uptr:
6079 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
6080 // with the MS modifier keyword.
6081 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
6082 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
6083 if (TryKeywordIdentFallback(false))
6084 continue;
6086 [[fallthrough]];
6087 case tok::kw___sptr:
6088 case tok::kw___w64:
6089 case tok::kw___ptr64:
6090 case tok::kw___ptr32:
6091 case tok::kw___cdecl:
6092 case tok::kw___stdcall:
6093 case tok::kw___fastcall:
6094 case tok::kw___thiscall:
6095 case tok::kw___regcall:
6096 case tok::kw___vectorcall:
6097 if (AttrReqs & AR_DeclspecAttributesParsed) {
6098 ParseMicrosoftTypeAttributes(DS.getAttributes());
6099 continue;
6101 goto DoneWithTypeQuals;
6103 case tok::kw___funcref:
6104 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
6105 continue;
6106 goto DoneWithTypeQuals;
6108 case tok::kw___pascal:
6109 if (AttrReqs & AR_VendorAttributesParsed) {
6110 ParseBorlandTypeAttributes(DS.getAttributes());
6111 continue;
6113 goto DoneWithTypeQuals;
6115 // Nullability type specifiers.
6116 case tok::kw__Nonnull:
6117 case tok::kw__Nullable:
6118 case tok::kw__Nullable_result:
6119 case tok::kw__Null_unspecified:
6120 ParseNullabilityTypeSpecifiers(DS.getAttributes());
6121 continue;
6123 // Objective-C 'kindof' types.
6124 case tok::kw___kindof:
6125 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
6126 nullptr, 0, tok::kw___kindof);
6127 (void)ConsumeToken();
6128 continue;
6130 case tok::kw___attribute:
6131 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
6132 // When GNU attributes are expressly forbidden, diagnose their usage.
6133 Diag(Tok, diag::err_attributes_not_allowed);
6135 // Parse the attributes even if they are rejected to ensure that error
6136 // recovery is graceful.
6137 if (AttrReqs & AR_GNUAttributesParsed ||
6138 AttrReqs & AR_GNUAttributesParsedAndRejected) {
6139 ParseGNUAttributes(DS.getAttributes());
6140 continue; // do *not* consume the next token!
6142 // otherwise, FALL THROUGH!
6143 [[fallthrough]];
6144 default:
6145 DoneWithTypeQuals:
6146 // If this is not a type-qualifier token, we're done reading type
6147 // qualifiers. First verify that DeclSpec's are consistent.
6148 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
6149 if (EndLoc.isValid())
6150 DS.SetRangeEnd(EndLoc);
6151 return;
6154 // If the specifier combination wasn't legal, issue a diagnostic.
6155 if (isInvalid) {
6156 assert(PrevSpec && "Method did not return previous specifier!");
6157 Diag(Tok, DiagID) << PrevSpec;
6159 EndLoc = ConsumeToken();
6163 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
6164 void Parser::ParseDeclarator(Declarator &D) {
6165 /// This implements the 'declarator' production in the C grammar, then checks
6166 /// for well-formedness and issues diagnostics.
6167 Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
6168 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6172 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
6173 DeclaratorContext TheContext) {
6174 if (Kind == tok::star || Kind == tok::caret)
6175 return true;
6177 // OpenCL 2.0 and later define this keyword.
6178 if (Kind == tok::kw_pipe && Lang.OpenCL &&
6179 Lang.getOpenCLCompatibleVersion() >= 200)
6180 return true;
6182 if (!Lang.CPlusPlus)
6183 return false;
6185 if (Kind == tok::amp)
6186 return true;
6188 // We parse rvalue refs in C++03, because otherwise the errors are scary.
6189 // But we must not parse them in conversion-type-ids and new-type-ids, since
6190 // those can be legitimately followed by a && operator.
6191 // (The same thing can in theory happen after a trailing-return-type, but
6192 // since those are a C++11 feature, there is no rejects-valid issue there.)
6193 if (Kind == tok::ampamp)
6194 return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId &&
6195 TheContext != DeclaratorContext::CXXNew);
6197 return false;
6200 // Indicates whether the given declarator is a pipe declarator.
6201 static bool isPipeDeclarator(const Declarator &D) {
6202 const unsigned NumTypes = D.getNumTypeObjects();
6204 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
6205 if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
6206 return true;
6208 return false;
6211 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
6212 /// is parsed by the function passed to it. Pass null, and the direct-declarator
6213 /// isn't parsed at all, making this function effectively parse the C++
6214 /// ptr-operator production.
6216 /// If the grammar of this construct is extended, matching changes must also be
6217 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
6218 /// isConstructorDeclarator.
6220 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
6221 /// [C] pointer[opt] direct-declarator
6222 /// [C++] direct-declarator
6223 /// [C++] ptr-operator declarator
6225 /// pointer: [C99 6.7.5]
6226 /// '*' type-qualifier-list[opt]
6227 /// '*' type-qualifier-list[opt] pointer
6229 /// ptr-operator:
6230 /// '*' cv-qualifier-seq[opt]
6231 /// '&'
6232 /// [C++0x] '&&'
6233 /// [GNU] '&' restrict[opt] attributes[opt]
6234 /// [GNU?] '&&' restrict[opt] attributes[opt]
6235 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
6236 void Parser::ParseDeclaratorInternal(Declarator &D,
6237 DirectDeclParseFunction DirectDeclParser) {
6238 if (Diags.hasAllExtensionsSilenced())
6239 D.setExtension();
6241 // C++ member pointers start with a '::' or a nested-name.
6242 // Member pointers get special handling, since there's no place for the
6243 // scope spec in the generic path below.
6244 if (getLangOpts().CPlusPlus &&
6245 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
6246 (Tok.is(tok::identifier) &&
6247 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
6248 Tok.is(tok::annot_cxxscope))) {
6249 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6250 D.getContext() == DeclaratorContext::Member;
6251 CXXScopeSpec SS;
6252 SS.setTemplateParamLists(D.getTemplateParameterLists());
6253 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6254 /*ObjectHasErrors=*/false, EnteringContext);
6256 if (SS.isNotEmpty()) {
6257 if (Tok.isNot(tok::star)) {
6258 // The scope spec really belongs to the direct-declarator.
6259 if (D.mayHaveIdentifier())
6260 D.getCXXScopeSpec() = SS;
6261 else
6262 AnnotateScopeToken(SS, true);
6264 if (DirectDeclParser)
6265 (this->*DirectDeclParser)(D);
6266 return;
6269 if (SS.isValid()) {
6270 checkCompoundToken(SS.getEndLoc(), tok::coloncolon,
6271 CompoundToken::MemberPtr);
6274 SourceLocation StarLoc = ConsumeToken();
6275 D.SetRangeEnd(StarLoc);
6276 DeclSpec DS(AttrFactory);
6277 ParseTypeQualifierListOpt(DS);
6278 D.ExtendWithDeclSpec(DS);
6280 // Recurse to parse whatever is left.
6281 Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
6282 ParseDeclaratorInternal(D, DirectDeclParser);
6285 // Sema will have to catch (syntactically invalid) pointers into global
6286 // scope. It has to catch pointers into namespace scope anyway.
6287 D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
6288 SS, DS.getTypeQualifiers(), StarLoc, DS.getEndLoc()),
6289 std::move(DS.getAttributes()),
6290 /* Don't replace range end. */ SourceLocation());
6291 return;
6295 tok::TokenKind Kind = Tok.getKind();
6297 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclarator(D)) {
6298 DeclSpec DS(AttrFactory);
6299 ParseTypeQualifierListOpt(DS);
6301 D.AddTypeInfo(
6302 DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
6303 std::move(DS.getAttributes()), SourceLocation());
6306 // Not a pointer, C++ reference, or block.
6307 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
6308 if (DirectDeclParser)
6309 (this->*DirectDeclParser)(D);
6310 return;
6313 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
6314 // '&&' -> rvalue reference
6315 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
6316 D.SetRangeEnd(Loc);
6318 if (Kind == tok::star || Kind == tok::caret) {
6319 // Is a pointer.
6320 DeclSpec DS(AttrFactory);
6322 // GNU attributes are not allowed here in a new-type-id, but Declspec and
6323 // C++11 attributes are allowed.
6324 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
6325 ((D.getContext() != DeclaratorContext::CXXNew)
6326 ? AR_GNUAttributesParsed
6327 : AR_GNUAttributesParsedAndRejected);
6328 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
6329 D.ExtendWithDeclSpec(DS);
6331 // Recursively parse the declarator.
6332 Actions.runWithSufficientStackSpace(
6333 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6334 if (Kind == tok::star)
6335 // Remember that we parsed a pointer type, and remember the type-quals.
6336 D.AddTypeInfo(DeclaratorChunk::getPointer(
6337 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
6338 DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
6339 DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
6340 std::move(DS.getAttributes()), SourceLocation());
6341 else
6342 // Remember that we parsed a Block type, and remember the type-quals.
6343 D.AddTypeInfo(
6344 DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
6345 std::move(DS.getAttributes()), SourceLocation());
6346 } else {
6347 // Is a reference
6348 DeclSpec DS(AttrFactory);
6350 // Complain about rvalue references in C++03, but then go on and build
6351 // the declarator.
6352 if (Kind == tok::ampamp)
6353 Diag(Loc, getLangOpts().CPlusPlus11 ?
6354 diag::warn_cxx98_compat_rvalue_reference :
6355 diag::ext_rvalue_reference);
6357 // GNU-style and C++11 attributes are allowed here, as is restrict.
6358 ParseTypeQualifierListOpt(DS);
6359 D.ExtendWithDeclSpec(DS);
6361 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
6362 // cv-qualifiers are introduced through the use of a typedef or of a
6363 // template type argument, in which case the cv-qualifiers are ignored.
6364 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
6365 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
6366 Diag(DS.getConstSpecLoc(),
6367 diag::err_invalid_reference_qualifier_application) << "const";
6368 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
6369 Diag(DS.getVolatileSpecLoc(),
6370 diag::err_invalid_reference_qualifier_application) << "volatile";
6371 // 'restrict' is permitted as an extension.
6372 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
6373 Diag(DS.getAtomicSpecLoc(),
6374 diag::err_invalid_reference_qualifier_application) << "_Atomic";
6377 // Recursively parse the declarator.
6378 Actions.runWithSufficientStackSpace(
6379 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6381 if (D.getNumTypeObjects() > 0) {
6382 // C++ [dcl.ref]p4: There shall be no references to references.
6383 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
6384 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
6385 if (const IdentifierInfo *II = D.getIdentifier())
6386 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6387 << II;
6388 else
6389 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6390 << "type name";
6392 // Once we've complained about the reference-to-reference, we
6393 // can go ahead and build the (technically ill-formed)
6394 // declarator: reference collapsing will take care of it.
6398 // Remember that we parsed a reference type.
6399 D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
6400 Kind == tok::amp),
6401 std::move(DS.getAttributes()), SourceLocation());
6405 // When correcting from misplaced brackets before the identifier, the location
6406 // is saved inside the declarator so that other diagnostic messages can use
6407 // them. This extracts and returns that location, or returns the provided
6408 // location if a stored location does not exist.
6409 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
6410 SourceLocation Loc) {
6411 if (D.getName().StartLocation.isInvalid() &&
6412 D.getName().EndLocation.isValid())
6413 return D.getName().EndLocation;
6415 return Loc;
6418 /// ParseDirectDeclarator
6419 /// direct-declarator: [C99 6.7.5]
6420 /// [C99] identifier
6421 /// '(' declarator ')'
6422 /// [GNU] '(' attributes declarator ')'
6423 /// [C90] direct-declarator '[' constant-expression[opt] ']'
6424 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6425 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6426 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6427 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6428 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6429 /// attribute-specifier-seq[opt]
6430 /// direct-declarator '(' parameter-type-list ')'
6431 /// direct-declarator '(' identifier-list[opt] ')'
6432 /// [GNU] direct-declarator '(' parameter-forward-declarations
6433 /// parameter-type-list[opt] ')'
6434 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
6435 /// cv-qualifier-seq[opt] exception-specification[opt]
6436 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
6437 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
6438 /// ref-qualifier[opt] exception-specification[opt]
6439 /// [C++] declarator-id
6440 /// [C++11] declarator-id attribute-specifier-seq[opt]
6442 /// declarator-id: [C++ 8]
6443 /// '...'[opt] id-expression
6444 /// '::'[opt] nested-name-specifier[opt] type-name
6446 /// id-expression: [C++ 5.1]
6447 /// unqualified-id
6448 /// qualified-id
6450 /// unqualified-id: [C++ 5.1]
6451 /// identifier
6452 /// operator-function-id
6453 /// conversion-function-id
6454 /// '~' class-name
6455 /// template-id
6457 /// C++17 adds the following, which we also handle here:
6459 /// simple-declaration:
6460 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
6462 /// Note, any additional constructs added here may need corresponding changes
6463 /// in isConstructorDeclarator.
6464 void Parser::ParseDirectDeclarator(Declarator &D) {
6465 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
6467 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
6468 // This might be a C++17 structured binding.
6469 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
6470 D.getCXXScopeSpec().isEmpty())
6471 return ParseDecompositionDeclarator(D);
6473 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
6474 // this context it is a bitfield. Also in range-based for statement colon
6475 // may delimit for-range-declaration.
6476 ColonProtectionRAIIObject X(
6477 *this, D.getContext() == DeclaratorContext::Member ||
6478 (D.getContext() == DeclaratorContext::ForInit &&
6479 getLangOpts().CPlusPlus11));
6481 // ParseDeclaratorInternal might already have parsed the scope.
6482 if (D.getCXXScopeSpec().isEmpty()) {
6483 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6484 D.getContext() == DeclaratorContext::Member;
6485 ParseOptionalCXXScopeSpecifier(
6486 D.getCXXScopeSpec(), /*ObjectType=*/nullptr,
6487 /*ObjectHasErrors=*/false, EnteringContext);
6490 if (D.getCXXScopeSpec().isValid()) {
6491 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
6492 D.getCXXScopeSpec()))
6493 // Change the declaration context for name lookup, until this function
6494 // is exited (and the declarator has been parsed).
6495 DeclScopeObj.EnterDeclaratorScope();
6496 else if (getObjCDeclContext()) {
6497 // Ensure that we don't interpret the next token as an identifier when
6498 // dealing with declarations in an Objective-C container.
6499 D.SetIdentifier(nullptr, Tok.getLocation());
6500 D.setInvalidType(true);
6501 ConsumeToken();
6502 goto PastIdentifier;
6506 // C++0x [dcl.fct]p14:
6507 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
6508 // parameter-declaration-clause without a preceding comma. In this case,
6509 // the ellipsis is parsed as part of the abstract-declarator if the type
6510 // of the parameter either names a template parameter pack that has not
6511 // been expanded or contains auto; otherwise, it is parsed as part of the
6512 // parameter-declaration-clause.
6513 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
6514 !((D.getContext() == DeclaratorContext::Prototype ||
6515 D.getContext() == DeclaratorContext::LambdaExprParameter ||
6516 D.getContext() == DeclaratorContext::BlockLiteral) &&
6517 NextToken().is(tok::r_paren) && !D.hasGroupingParens() &&
6518 !Actions.containsUnexpandedParameterPacks(D) &&
6519 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
6520 SourceLocation EllipsisLoc = ConsumeToken();
6521 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
6522 // The ellipsis was put in the wrong place. Recover, and explain to
6523 // the user what they should have done.
6524 ParseDeclarator(D);
6525 if (EllipsisLoc.isValid())
6526 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6527 return;
6528 } else
6529 D.setEllipsisLoc(EllipsisLoc);
6531 // The ellipsis can't be followed by a parenthesized declarator. We
6532 // check for that in ParseParenDeclarator, after we have disambiguated
6533 // the l_paren token.
6536 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
6537 tok::tilde)) {
6538 // We found something that indicates the start of an unqualified-id.
6539 // Parse that unqualified-id.
6540 bool AllowConstructorName;
6541 bool AllowDeductionGuide;
6542 if (D.getDeclSpec().hasTypeSpecifier()) {
6543 AllowConstructorName = false;
6544 AllowDeductionGuide = false;
6545 } else if (D.getCXXScopeSpec().isSet()) {
6546 AllowConstructorName = (D.getContext() == DeclaratorContext::File ||
6547 D.getContext() == DeclaratorContext::Member);
6548 AllowDeductionGuide = false;
6549 } else {
6550 AllowConstructorName = (D.getContext() == DeclaratorContext::Member);
6551 AllowDeductionGuide = (D.getContext() == DeclaratorContext::File ||
6552 D.getContext() == DeclaratorContext::Member);
6555 bool HadScope = D.getCXXScopeSpec().isValid();
6556 if (ParseUnqualifiedId(D.getCXXScopeSpec(),
6557 /*ObjectType=*/nullptr,
6558 /*ObjectHadErrors=*/false,
6559 /*EnteringContext=*/true,
6560 /*AllowDestructorName=*/true, AllowConstructorName,
6561 AllowDeductionGuide, nullptr, D.getName()) ||
6562 // Once we're past the identifier, if the scope was bad, mark the
6563 // whole declarator bad.
6564 D.getCXXScopeSpec().isInvalid()) {
6565 D.SetIdentifier(nullptr, Tok.getLocation());
6566 D.setInvalidType(true);
6567 } else {
6568 // ParseUnqualifiedId might have parsed a scope specifier during error
6569 // recovery. If it did so, enter that scope.
6570 if (!HadScope && D.getCXXScopeSpec().isValid() &&
6571 Actions.ShouldEnterDeclaratorScope(getCurScope(),
6572 D.getCXXScopeSpec()))
6573 DeclScopeObj.EnterDeclaratorScope();
6575 // Parsed the unqualified-id; update range information and move along.
6576 if (D.getSourceRange().getBegin().isInvalid())
6577 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
6578 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
6580 goto PastIdentifier;
6583 if (D.getCXXScopeSpec().isNotEmpty()) {
6584 // We have a scope specifier but no following unqualified-id.
6585 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
6586 diag::err_expected_unqualified_id)
6587 << /*C++*/1;
6588 D.SetIdentifier(nullptr, Tok.getLocation());
6589 goto PastIdentifier;
6591 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
6592 assert(!getLangOpts().CPlusPlus &&
6593 "There's a C++-specific check for tok::identifier above");
6594 assert(Tok.getIdentifierInfo() && "Not an identifier?");
6595 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
6596 D.SetRangeEnd(Tok.getLocation());
6597 ConsumeToken();
6598 goto PastIdentifier;
6599 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
6600 // We're not allowed an identifier here, but we got one. Try to figure out
6601 // if the user was trying to attach a name to the type, or whether the name
6602 // is some unrelated trailing syntax.
6603 bool DiagnoseIdentifier = false;
6604 if (D.hasGroupingParens())
6605 // An identifier within parens is unlikely to be intended to be anything
6606 // other than a name being "declared".
6607 DiagnoseIdentifier = true;
6608 else if (D.getContext() == DeclaratorContext::TemplateArg)
6609 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
6610 DiagnoseIdentifier =
6611 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
6612 else if (D.getContext() == DeclaratorContext::AliasDecl ||
6613 D.getContext() == DeclaratorContext::AliasTemplate)
6614 // The most likely error is that the ';' was forgotten.
6615 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
6616 else if ((D.getContext() == DeclaratorContext::TrailingReturn ||
6617 D.getContext() == DeclaratorContext::TrailingReturnVar) &&
6618 !isCXX11VirtSpecifier(Tok))
6619 DiagnoseIdentifier = NextToken().isOneOf(
6620 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
6621 if (DiagnoseIdentifier) {
6622 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
6623 << FixItHint::CreateRemoval(Tok.getLocation());
6624 D.SetIdentifier(nullptr, Tok.getLocation());
6625 ConsumeToken();
6626 goto PastIdentifier;
6630 if (Tok.is(tok::l_paren)) {
6631 // If this might be an abstract-declarator followed by a direct-initializer,
6632 // check whether this is a valid declarator chunk. If it can't be, assume
6633 // that it's an initializer instead.
6634 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
6635 RevertingTentativeParsingAction PA(*this);
6636 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true,
6637 D.getDeclSpec().getTypeSpecType() == TST_auto) ==
6638 TPResult::False) {
6639 D.SetIdentifier(nullptr, Tok.getLocation());
6640 goto PastIdentifier;
6644 // direct-declarator: '(' declarator ')'
6645 // direct-declarator: '(' attributes declarator ')'
6646 // Example: 'char (*X)' or 'int (*XX)(void)'
6647 ParseParenDeclarator(D);
6649 // If the declarator was parenthesized, we entered the declarator
6650 // scope when parsing the parenthesized declarator, then exited
6651 // the scope already. Re-enter the scope, if we need to.
6652 if (D.getCXXScopeSpec().isSet()) {
6653 // If there was an error parsing parenthesized declarator, declarator
6654 // scope may have been entered before. Don't do it again.
6655 if (!D.isInvalidType() &&
6656 Actions.ShouldEnterDeclaratorScope(getCurScope(),
6657 D.getCXXScopeSpec()))
6658 // Change the declaration context for name lookup, until this function
6659 // is exited (and the declarator has been parsed).
6660 DeclScopeObj.EnterDeclaratorScope();
6662 } else if (D.mayOmitIdentifier()) {
6663 // This could be something simple like "int" (in which case the declarator
6664 // portion is empty), if an abstract-declarator is allowed.
6665 D.SetIdentifier(nullptr, Tok.getLocation());
6667 // The grammar for abstract-pack-declarator does not allow grouping parens.
6668 // FIXME: Revisit this once core issue 1488 is resolved.
6669 if (D.hasEllipsis() && D.hasGroupingParens())
6670 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
6671 diag::ext_abstract_pack_declarator_parens);
6672 } else {
6673 if (Tok.getKind() == tok::annot_pragma_parser_crash)
6674 LLVM_BUILTIN_TRAP;
6675 if (Tok.is(tok::l_square))
6676 return ParseMisplacedBracketDeclarator(D);
6677 if (D.getContext() == DeclaratorContext::Member) {
6678 // Objective-C++: Detect C++ keywords and try to prevent further errors by
6679 // treating these keyword as valid member names.
6680 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
6681 !Tok.isAnnotation() && Tok.getIdentifierInfo() &&
6682 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
6683 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6684 diag::err_expected_member_name_or_semi_objcxx_keyword)
6685 << Tok.getIdentifierInfo()
6686 << (D.getDeclSpec().isEmpty() ? SourceRange()
6687 : D.getDeclSpec().getSourceRange());
6688 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
6689 D.SetRangeEnd(Tok.getLocation());
6690 ConsumeToken();
6691 goto PastIdentifier;
6693 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6694 diag::err_expected_member_name_or_semi)
6695 << (D.getDeclSpec().isEmpty() ? SourceRange()
6696 : D.getDeclSpec().getSourceRange());
6697 } else {
6698 if (Tok.getKind() == tok::TokenKind::kw_while) {
6699 Diag(Tok, diag::err_while_loop_outside_of_a_function);
6700 } else if (getLangOpts().CPlusPlus) {
6701 if (Tok.isOneOf(tok::period, tok::arrow))
6702 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
6703 else {
6704 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
6705 if (Tok.isAtStartOfLine() && Loc.isValid())
6706 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
6707 << getLangOpts().CPlusPlus;
6708 else
6709 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6710 diag::err_expected_unqualified_id)
6711 << getLangOpts().CPlusPlus;
6713 } else {
6714 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6715 diag::err_expected_either)
6716 << tok::identifier << tok::l_paren;
6719 D.SetIdentifier(nullptr, Tok.getLocation());
6720 D.setInvalidType(true);
6723 PastIdentifier:
6724 assert(D.isPastIdentifier() &&
6725 "Haven't past the location of the identifier yet?");
6727 // Don't parse attributes unless we have parsed an unparenthesized name.
6728 if (D.hasName() && !D.getNumTypeObjects())
6729 MaybeParseCXX11Attributes(D);
6731 while (true) {
6732 if (Tok.is(tok::l_paren)) {
6733 bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
6734 // Enter function-declaration scope, limiting any declarators to the
6735 // function prototype scope, including parameter declarators.
6736 ParseScope PrototypeScope(this,
6737 Scope::FunctionPrototypeScope|Scope::DeclScope|
6738 (IsFunctionDeclaration
6739 ? Scope::FunctionDeclarationScope : 0));
6741 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
6742 // In such a case, check if we actually have a function declarator; if it
6743 // is not, the declarator has been fully parsed.
6744 bool IsAmbiguous = false;
6745 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
6746 // C++2a [temp.res]p5
6747 // A qualified-id is assumed to name a type if
6748 // - [...]
6749 // - it is a decl-specifier of the decl-specifier-seq of a
6750 // - [...]
6751 // - parameter-declaration in a member-declaration [...]
6752 // - parameter-declaration in a declarator of a function or function
6753 // template declaration whose declarator-id is qualified [...]
6754 auto AllowImplicitTypename = ImplicitTypenameContext::No;
6755 if (D.getCXXScopeSpec().isSet())
6756 AllowImplicitTypename =
6757 (ImplicitTypenameContext)Actions.isDeclaratorFunctionLike(D);
6758 else if (D.getContext() == DeclaratorContext::Member) {
6759 AllowImplicitTypename = ImplicitTypenameContext::Yes;
6762 // The name of the declarator, if any, is tentatively declared within
6763 // a possible direct initializer.
6764 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
6765 bool IsFunctionDecl =
6766 isCXXFunctionDeclarator(&IsAmbiguous, AllowImplicitTypename);
6767 TentativelyDeclaredIdentifiers.pop_back();
6768 if (!IsFunctionDecl)
6769 break;
6771 ParsedAttributes attrs(AttrFactory);
6772 BalancedDelimiterTracker T(*this, tok::l_paren);
6773 T.consumeOpen();
6774 if (IsFunctionDeclaration)
6775 Actions.ActOnStartFunctionDeclarationDeclarator(D,
6776 TemplateParameterDepth);
6777 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
6778 if (IsFunctionDeclaration)
6779 Actions.ActOnFinishFunctionDeclarationDeclarator(D);
6780 PrototypeScope.Exit();
6781 } else if (Tok.is(tok::l_square)) {
6782 ParseBracketDeclarator(D);
6783 } else if (Tok.isRegularKeywordAttribute()) {
6784 // For consistency with attribute parsing.
6785 Diag(Tok, diag::err_keyword_not_allowed) << Tok.getIdentifierInfo();
6786 ConsumeToken();
6787 } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
6788 // This declarator is declaring a function, but the requires clause is
6789 // in the wrong place:
6790 // void (f() requires true);
6791 // instead of
6792 // void f() requires true;
6793 // or
6794 // void (f()) requires true;
6795 Diag(Tok, diag::err_requires_clause_inside_parens);
6796 ConsumeToken();
6797 ExprResult TrailingRequiresClause = Actions.CorrectDelayedTyposInExpr(
6798 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6799 if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
6800 !D.hasTrailingRequiresClause())
6801 // We're already ill-formed if we got here but we'll accept it anyway.
6802 D.setTrailingRequiresClause(TrailingRequiresClause.get());
6803 } else {
6804 break;
6809 void Parser::ParseDecompositionDeclarator(Declarator &D) {
6810 assert(Tok.is(tok::l_square));
6812 // If this doesn't look like a structured binding, maybe it's a misplaced
6813 // array declarator.
6814 // FIXME: Consume the l_square first so we don't need extra lookahead for
6815 // this.
6816 if (!(NextToken().is(tok::identifier) &&
6817 GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
6818 !(NextToken().is(tok::r_square) &&
6819 GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
6820 return ParseMisplacedBracketDeclarator(D);
6822 BalancedDelimiterTracker T(*this, tok::l_square);
6823 T.consumeOpen();
6825 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
6826 while (Tok.isNot(tok::r_square)) {
6827 if (!Bindings.empty()) {
6828 if (Tok.is(tok::comma))
6829 ConsumeToken();
6830 else {
6831 if (Tok.is(tok::identifier)) {
6832 SourceLocation EndLoc = getEndOfPreviousToken();
6833 Diag(EndLoc, diag::err_expected)
6834 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
6835 } else {
6836 Diag(Tok, diag::err_expected_comma_or_rsquare);
6839 SkipUntil(tok::r_square, tok::comma, tok::identifier,
6840 StopAtSemi | StopBeforeMatch);
6841 if (Tok.is(tok::comma))
6842 ConsumeToken();
6843 else if (Tok.isNot(tok::identifier))
6844 break;
6848 if (Tok.isNot(tok::identifier)) {
6849 Diag(Tok, diag::err_expected) << tok::identifier;
6850 break;
6853 Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6854 ConsumeToken();
6857 if (Tok.isNot(tok::r_square))
6858 // We've already diagnosed a problem here.
6859 T.skipToEnd();
6860 else {
6861 // C++17 does not allow the identifier-list in a structured binding
6862 // to be empty.
6863 if (Bindings.empty())
6864 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6866 T.consumeClose();
6869 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6870 T.getCloseLocation());
6873 /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
6874 /// only called before the identifier, so these are most likely just grouping
6875 /// parens for precedence. If we find that these are actually function
6876 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6878 /// direct-declarator:
6879 /// '(' declarator ')'
6880 /// [GNU] '(' attributes declarator ')'
6881 /// direct-declarator '(' parameter-type-list ')'
6882 /// direct-declarator '(' identifier-list[opt] ')'
6883 /// [GNU] direct-declarator '(' parameter-forward-declarations
6884 /// parameter-type-list[opt] ')'
6886 void Parser::ParseParenDeclarator(Declarator &D) {
6887 BalancedDelimiterTracker T(*this, tok::l_paren);
6888 T.consumeOpen();
6890 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
6892 // Eat any attributes before we look at whether this is a grouping or function
6893 // declarator paren. If this is a grouping paren, the attribute applies to
6894 // the type being built up, for example:
6895 // int (__attribute__(()) *x)(long y)
6896 // If this ends up not being a grouping paren, the attribute applies to the
6897 // first argument, for example:
6898 // int (__attribute__(()) int x)
6899 // In either case, we need to eat any attributes to be able to determine what
6900 // sort of paren this is.
6902 ParsedAttributes attrs(AttrFactory);
6903 bool RequiresArg = false;
6904 if (Tok.is(tok::kw___attribute)) {
6905 ParseGNUAttributes(attrs);
6907 // We require that the argument list (if this is a non-grouping paren) be
6908 // present even if the attribute list was empty.
6909 RequiresArg = true;
6912 // Eat any Microsoft extensions.
6913 ParseMicrosoftTypeAttributes(attrs);
6915 // Eat any Borland extensions.
6916 if (Tok.is(tok::kw___pascal))
6917 ParseBorlandTypeAttributes(attrs);
6919 // If we haven't past the identifier yet (or where the identifier would be
6920 // stored, if this is an abstract declarator), then this is probably just
6921 // grouping parens. However, if this could be an abstract-declarator, then
6922 // this could also be the start of function arguments (consider 'void()').
6923 bool isGrouping;
6925 if (!D.mayOmitIdentifier()) {
6926 // If this can't be an abstract-declarator, this *must* be a grouping
6927 // paren, because we haven't seen the identifier yet.
6928 isGrouping = true;
6929 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
6930 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6931 NextToken().is(tok::r_paren)) || // C++ int(...)
6932 isDeclarationSpecifier(
6933 ImplicitTypenameContext::No) || // 'int(int)' is a function.
6934 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
6935 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6936 // considered to be a type, not a K&R identifier-list.
6937 isGrouping = false;
6938 } else {
6939 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6940 isGrouping = true;
6943 // If this is a grouping paren, handle:
6944 // direct-declarator: '(' declarator ')'
6945 // direct-declarator: '(' attributes declarator ')'
6946 if (isGrouping) {
6947 SourceLocation EllipsisLoc = D.getEllipsisLoc();
6948 D.setEllipsisLoc(SourceLocation());
6950 bool hadGroupingParens = D.hasGroupingParens();
6951 D.setGroupingParens(true);
6952 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6953 // Match the ')'.
6954 T.consumeClose();
6955 D.AddTypeInfo(
6956 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6957 std::move(attrs), T.getCloseLocation());
6959 D.setGroupingParens(hadGroupingParens);
6961 // An ellipsis cannot be placed outside parentheses.
6962 if (EllipsisLoc.isValid())
6963 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6965 return;
6968 // Okay, if this wasn't a grouping paren, it must be the start of a function
6969 // argument list. Recognize that this declarator will never have an
6970 // identifier (and remember where it would have been), then call into
6971 // ParseFunctionDeclarator to handle of argument list.
6972 D.SetIdentifier(nullptr, Tok.getLocation());
6974 // Enter function-declaration scope, limiting any declarators to the
6975 // function prototype scope, including parameter declarators.
6976 ParseScope PrototypeScope(this,
6977 Scope::FunctionPrototypeScope | Scope::DeclScope |
6978 (D.isFunctionDeclaratorAFunctionDeclaration()
6979 ? Scope::FunctionDeclarationScope : 0));
6980 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
6981 PrototypeScope.Exit();
6984 void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
6985 const Declarator &D, const DeclSpec &DS,
6986 std::optional<Sema::CXXThisScopeRAII> &ThisScope) {
6987 // C++11 [expr.prim.general]p3:
6988 // If a declaration declares a member function or member function
6989 // template of a class X, the expression this is a prvalue of type
6990 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6991 // and the end of the function-definition, member-declarator, or
6992 // declarator.
6993 // FIXME: currently, "static" case isn't handled correctly.
6994 bool IsCXX11MemberFunction =
6995 getLangOpts().CPlusPlus11 &&
6996 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6997 (D.getContext() == DeclaratorContext::Member
6998 ? !D.getDeclSpec().isFriendSpecified()
6999 : D.getContext() == DeclaratorContext::File &&
7000 D.getCXXScopeSpec().isValid() &&
7001 Actions.CurContext->isRecord());
7002 if (!IsCXX11MemberFunction)
7003 return;
7005 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
7006 if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
7007 Q.addConst();
7008 // FIXME: Collect C++ address spaces.
7009 // If there are multiple different address spaces, the source is invalid.
7010 // Carry on using the first addr space for the qualifiers of 'this'.
7011 // The diagnostic will be given later while creating the function
7012 // prototype for the method.
7013 if (getLangOpts().OpenCLCPlusPlus) {
7014 for (ParsedAttr &attr : DS.getAttributes()) {
7015 LangAS ASIdx = attr.asOpenCLLangAS();
7016 if (ASIdx != LangAS::Default) {
7017 Q.addAddressSpace(ASIdx);
7018 break;
7022 ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
7023 IsCXX11MemberFunction);
7026 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
7027 /// declarator D up to a paren, which indicates that we are parsing function
7028 /// arguments.
7030 /// If FirstArgAttrs is non-null, then the caller parsed those attributes
7031 /// immediately after the open paren - they will be applied to the DeclSpec
7032 /// of the first parameter.
7034 /// If RequiresArg is true, then the first argument of the function is required
7035 /// to be present and required to not be an identifier list.
7037 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
7038 /// (C++11) ref-qualifier[opt], exception-specification[opt],
7039 /// (C++11) attribute-specifier-seq[opt], (C++11) trailing-return-type[opt] and
7040 /// (C++2a) the trailing requires-clause.
7042 /// [C++11] exception-specification:
7043 /// dynamic-exception-specification
7044 /// noexcept-specification
7046 void Parser::ParseFunctionDeclarator(Declarator &D,
7047 ParsedAttributes &FirstArgAttrs,
7048 BalancedDelimiterTracker &Tracker,
7049 bool IsAmbiguous,
7050 bool RequiresArg) {
7051 assert(getCurScope()->isFunctionPrototypeScope() &&
7052 "Should call from a Function scope");
7053 // lparen is already consumed!
7054 assert(D.isPastIdentifier() && "Should not call before identifier!");
7056 // This should be true when the function has typed arguments.
7057 // Otherwise, it is treated as a K&R-style function.
7058 bool HasProto = false;
7059 // Build up an array of information about the parsed arguments.
7060 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
7061 // Remember where we see an ellipsis, if any.
7062 SourceLocation EllipsisLoc;
7064 DeclSpec DS(AttrFactory);
7065 bool RefQualifierIsLValueRef = true;
7066 SourceLocation RefQualifierLoc;
7067 ExceptionSpecificationType ESpecType = EST_None;
7068 SourceRange ESpecRange;
7069 SmallVector<ParsedType, 2> DynamicExceptions;
7070 SmallVector<SourceRange, 2> DynamicExceptionRanges;
7071 ExprResult NoexceptExpr;
7072 CachedTokens *ExceptionSpecTokens = nullptr;
7073 ParsedAttributes FnAttrs(AttrFactory);
7074 TypeResult TrailingReturnType;
7075 SourceLocation TrailingReturnTypeLoc;
7077 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
7078 EndLoc is the end location for the function declarator.
7079 They differ for trailing return types. */
7080 SourceLocation StartLoc, LocalEndLoc, EndLoc;
7081 SourceLocation LParenLoc, RParenLoc;
7082 LParenLoc = Tracker.getOpenLocation();
7083 StartLoc = LParenLoc;
7085 if (isFunctionDeclaratorIdentifierList()) {
7086 if (RequiresArg)
7087 Diag(Tok, diag::err_argument_required_after_attribute);
7089 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
7091 Tracker.consumeClose();
7092 RParenLoc = Tracker.getCloseLocation();
7093 LocalEndLoc = RParenLoc;
7094 EndLoc = RParenLoc;
7096 // If there are attributes following the identifier list, parse them and
7097 // prohibit them.
7098 MaybeParseCXX11Attributes(FnAttrs);
7099 ProhibitAttributes(FnAttrs);
7100 } else {
7101 if (Tok.isNot(tok::r_paren))
7102 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
7103 else if (RequiresArg)
7104 Diag(Tok, diag::err_argument_required_after_attribute);
7106 // OpenCL disallows functions without a prototype, but it doesn't enforce
7107 // strict prototypes as in C23 because it allows a function definition to
7108 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
7109 HasProto = ParamInfo.size() || getLangOpts().requiresStrictPrototypes() ||
7110 getLangOpts().OpenCL;
7112 // If we have the closing ')', eat it.
7113 Tracker.consumeClose();
7114 RParenLoc = Tracker.getCloseLocation();
7115 LocalEndLoc = RParenLoc;
7116 EndLoc = RParenLoc;
7118 if (getLangOpts().CPlusPlus) {
7119 // FIXME: Accept these components in any order, and produce fixits to
7120 // correct the order if the user gets it wrong. Ideally we should deal
7121 // with the pure-specifier in the same way.
7123 // Parse cv-qualifier-seq[opt].
7124 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
7125 /*AtomicAllowed*/ false,
7126 /*IdentifierRequired=*/false,
7127 llvm::function_ref<void()>([&]() {
7128 Actions.CodeCompleteFunctionQualifiers(DS, D);
7129 }));
7130 if (!DS.getSourceRange().getEnd().isInvalid()) {
7131 EndLoc = DS.getSourceRange().getEnd();
7134 // Parse ref-qualifier[opt].
7135 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
7136 EndLoc = RefQualifierLoc;
7138 std::optional<Sema::CXXThisScopeRAII> ThisScope;
7139 InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
7141 // Parse exception-specification[opt].
7142 // FIXME: Per [class.mem]p6, all exception-specifications at class scope
7143 // should be delayed, including those for non-members (eg, friend
7144 // declarations). But only applying this to member declarations is
7145 // consistent with what other implementations do.
7146 bool Delayed = D.isFirstDeclarationOfMember() &&
7147 D.isFunctionDeclaratorAFunctionDeclaration();
7148 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
7149 GetLookAheadToken(0).is(tok::kw_noexcept) &&
7150 GetLookAheadToken(1).is(tok::l_paren) &&
7151 GetLookAheadToken(2).is(tok::kw_noexcept) &&
7152 GetLookAheadToken(3).is(tok::l_paren) &&
7153 GetLookAheadToken(4).is(tok::identifier) &&
7154 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
7155 // HACK: We've got an exception-specification
7156 // noexcept(noexcept(swap(...)))
7157 // or
7158 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
7159 // on a 'swap' member function. This is a libstdc++ bug; the lookup
7160 // for 'swap' will only find the function we're currently declaring,
7161 // whereas it expects to find a non-member swap through ADL. Turn off
7162 // delayed parsing to give it a chance to find what it expects.
7163 Delayed = false;
7165 ESpecType = tryParseExceptionSpecification(Delayed,
7166 ESpecRange,
7167 DynamicExceptions,
7168 DynamicExceptionRanges,
7169 NoexceptExpr,
7170 ExceptionSpecTokens);
7171 if (ESpecType != EST_None)
7172 EndLoc = ESpecRange.getEnd();
7174 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
7175 // after the exception-specification.
7176 MaybeParseCXX11Attributes(FnAttrs);
7178 // Parse trailing-return-type[opt].
7179 LocalEndLoc = EndLoc;
7180 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
7181 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
7182 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
7183 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
7184 LocalEndLoc = Tok.getLocation();
7185 SourceRange Range;
7186 TrailingReturnType =
7187 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
7188 TrailingReturnTypeLoc = Range.getBegin();
7189 EndLoc = Range.getEnd();
7191 } else {
7192 MaybeParseCXX11Attributes(FnAttrs);
7196 // Collect non-parameter declarations from the prototype if this is a function
7197 // declaration. They will be moved into the scope of the function. Only do
7198 // this in C and not C++, where the decls will continue to live in the
7199 // surrounding context.
7200 SmallVector<NamedDecl *, 0> DeclsInPrototype;
7201 if (getCurScope()->isFunctionDeclarationScope() && !getLangOpts().CPlusPlus) {
7202 for (Decl *D : getCurScope()->decls()) {
7203 NamedDecl *ND = dyn_cast<NamedDecl>(D);
7204 if (!ND || isa<ParmVarDecl>(ND))
7205 continue;
7206 DeclsInPrototype.push_back(ND);
7208 // Sort DeclsInPrototype based on raw encoding of the source location.
7209 // Scope::decls() is iterating over a SmallPtrSet so sort the Decls before
7210 // moving to DeclContext. This provides a stable ordering for traversing
7211 // Decls in DeclContext, which is important for tasks like ASTWriter for
7212 // deterministic output.
7213 llvm::sort(DeclsInPrototype, [](Decl *D1, Decl *D2) {
7214 return D1->getLocation().getRawEncoding() <
7215 D2->getLocation().getRawEncoding();
7219 // Remember that we parsed a function type, and remember the attributes.
7220 D.AddTypeInfo(DeclaratorChunk::getFunction(
7221 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
7222 ParamInfo.size(), EllipsisLoc, RParenLoc,
7223 RefQualifierIsLValueRef, RefQualifierLoc,
7224 /*MutableLoc=*/SourceLocation(),
7225 ESpecType, ESpecRange, DynamicExceptions.data(),
7226 DynamicExceptionRanges.data(), DynamicExceptions.size(),
7227 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
7228 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
7229 LocalEndLoc, D, TrailingReturnType, TrailingReturnTypeLoc,
7230 &DS),
7231 std::move(FnAttrs), EndLoc);
7234 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
7235 /// true if a ref-qualifier is found.
7236 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
7237 SourceLocation &RefQualifierLoc) {
7238 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
7239 Diag(Tok, getLangOpts().CPlusPlus11 ?
7240 diag::warn_cxx98_compat_ref_qualifier :
7241 diag::ext_ref_qualifier);
7243 RefQualifierIsLValueRef = Tok.is(tok::amp);
7244 RefQualifierLoc = ConsumeToken();
7245 return true;
7247 return false;
7250 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
7251 /// identifier list form for a K&R-style function: void foo(a,b,c)
7253 /// Note that identifier-lists are only allowed for normal declarators, not for
7254 /// abstract-declarators.
7255 bool Parser::isFunctionDeclaratorIdentifierList() {
7256 return !getLangOpts().requiresStrictPrototypes()
7257 && Tok.is(tok::identifier)
7258 && !TryAltiVecVectorToken()
7259 // K&R identifier lists can't have typedefs as identifiers, per C99
7260 // 6.7.5.3p11.
7261 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
7262 // Identifier lists follow a really simple grammar: the identifiers can
7263 // be followed *only* by a ", identifier" or ")". However, K&R
7264 // identifier lists are really rare in the brave new modern world, and
7265 // it is very common for someone to typo a type in a non-K&R style
7266 // list. If we are presented with something like: "void foo(intptr x,
7267 // float y)", we don't want to start parsing the function declarator as
7268 // though it is a K&R style declarator just because intptr is an
7269 // invalid type.
7271 // To handle this, we check to see if the token after the first
7272 // identifier is a "," or ")". Only then do we parse it as an
7273 // identifier list.
7274 && (!Tok.is(tok::eof) &&
7275 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
7278 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
7279 /// we found a K&R-style identifier list instead of a typed parameter list.
7281 /// After returning, ParamInfo will hold the parsed parameters.
7283 /// identifier-list: [C99 6.7.5]
7284 /// identifier
7285 /// identifier-list ',' identifier
7287 void Parser::ParseFunctionDeclaratorIdentifierList(
7288 Declarator &D,
7289 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
7290 // We should never reach this point in C23 or C++.
7291 assert(!getLangOpts().requiresStrictPrototypes() &&
7292 "Cannot parse an identifier list in C23 or C++");
7294 // If there was no identifier specified for the declarator, either we are in
7295 // an abstract-declarator, or we are in a parameter declarator which was found
7296 // to be abstract. In abstract-declarators, identifier lists are not valid:
7297 // diagnose this.
7298 if (!D.getIdentifier())
7299 Diag(Tok, diag::ext_ident_list_in_param);
7301 // Maintain an efficient lookup of params we have seen so far.
7302 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
7304 do {
7305 // If this isn't an identifier, report the error and skip until ')'.
7306 if (Tok.isNot(tok::identifier)) {
7307 Diag(Tok, diag::err_expected) << tok::identifier;
7308 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
7309 // Forget we parsed anything.
7310 ParamInfo.clear();
7311 return;
7314 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
7316 // Reject 'typedef int y; int test(x, y)', but continue parsing.
7317 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
7318 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
7320 // Verify that the argument identifier has not already been mentioned.
7321 if (!ParamsSoFar.insert(ParmII).second) {
7322 Diag(Tok, diag::err_param_redefinition) << ParmII;
7323 } else {
7324 // Remember this identifier in ParamInfo.
7325 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7326 Tok.getLocation(),
7327 nullptr));
7330 // Eat the identifier.
7331 ConsumeToken();
7332 // The list continues if we see a comma.
7333 } while (TryConsumeToken(tok::comma));
7336 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
7337 /// after the opening parenthesis. This function will not parse a K&R-style
7338 /// identifier list.
7340 /// DeclContext is the context of the declarator being parsed. If FirstArgAttrs
7341 /// is non-null, then the caller parsed those attributes immediately after the
7342 /// open paren - they will be applied to the DeclSpec of the first parameter.
7344 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
7345 /// be the location of the ellipsis, if any was parsed.
7347 /// parameter-type-list: [C99 6.7.5]
7348 /// parameter-list
7349 /// parameter-list ',' '...'
7350 /// [C++] parameter-list '...'
7352 /// parameter-list: [C99 6.7.5]
7353 /// parameter-declaration
7354 /// parameter-list ',' parameter-declaration
7356 /// parameter-declaration: [C99 6.7.5]
7357 /// declaration-specifiers declarator
7358 /// [C++] declaration-specifiers declarator '=' assignment-expression
7359 /// [C++11] initializer-clause
7360 /// [GNU] declaration-specifiers declarator attributes
7361 /// declaration-specifiers abstract-declarator[opt]
7362 /// [C++] declaration-specifiers abstract-declarator[opt]
7363 /// '=' assignment-expression
7364 /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
7365 /// [C++11] attribute-specifier-seq parameter-declaration
7366 /// [C++2b] attribute-specifier-seq 'this' parameter-declaration
7368 void Parser::ParseParameterDeclarationClause(
7369 DeclaratorContext DeclaratorCtx, ParsedAttributes &FirstArgAttrs,
7370 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
7371 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration) {
7373 // Avoid exceeding the maximum function scope depth.
7374 // See https://bugs.llvm.org/show_bug.cgi?id=19607
7375 // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
7376 // getFunctionPrototypeDepth() - 1.
7377 if (getCurScope()->getFunctionPrototypeDepth() - 1 >
7378 ParmVarDecl::getMaxFunctionScopeDepth()) {
7379 Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
7380 << ParmVarDecl::getMaxFunctionScopeDepth();
7381 cutOffParsing();
7382 return;
7385 // C++2a [temp.res]p5
7386 // A qualified-id is assumed to name a type if
7387 // - [...]
7388 // - it is a decl-specifier of the decl-specifier-seq of a
7389 // - [...]
7390 // - parameter-declaration in a member-declaration [...]
7391 // - parameter-declaration in a declarator of a function or function
7392 // template declaration whose declarator-id is qualified [...]
7393 // - parameter-declaration in a lambda-declarator [...]
7394 auto AllowImplicitTypename = ImplicitTypenameContext::No;
7395 if (DeclaratorCtx == DeclaratorContext::Member ||
7396 DeclaratorCtx == DeclaratorContext::LambdaExpr ||
7397 DeclaratorCtx == DeclaratorContext::RequiresExpr ||
7398 IsACXXFunctionDeclaration) {
7399 AllowImplicitTypename = ImplicitTypenameContext::Yes;
7402 do {
7403 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
7404 // before deciding this was a parameter-declaration-clause.
7405 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
7406 break;
7408 // Parse the declaration-specifiers.
7409 // Just use the ParsingDeclaration "scope" of the declarator.
7410 DeclSpec DS(AttrFactory);
7412 ParsedAttributes ArgDeclAttrs(AttrFactory);
7413 ParsedAttributes ArgDeclSpecAttrs(AttrFactory);
7415 if (FirstArgAttrs.Range.isValid()) {
7416 // If the caller parsed attributes for the first argument, add them now.
7417 // Take them so that we only apply the attributes to the first parameter.
7418 // We have already started parsing the decl-specifier sequence, so don't
7419 // parse any parameter-declaration pieces that precede it.
7420 ArgDeclSpecAttrs.takeAllFrom(FirstArgAttrs);
7421 } else {
7422 // Parse any C++11 attributes.
7423 MaybeParseCXX11Attributes(ArgDeclAttrs);
7425 // Skip any Microsoft attributes before a param.
7426 MaybeParseMicrosoftAttributes(ArgDeclSpecAttrs);
7429 SourceLocation DSStart = Tok.getLocation();
7431 // Parse a C++23 Explicit Object Parameter
7432 // We do that in all language modes to produce a better diagnostic.
7433 SourceLocation ThisLoc;
7434 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_this))
7435 ThisLoc = ConsumeToken();
7437 ParseDeclarationSpecifiers(DS, /*TemplateInfo=*/ParsedTemplateInfo(),
7438 AS_none, DeclSpecContext::DSC_normal,
7439 /*LateAttrs=*/nullptr, AllowImplicitTypename);
7441 DS.takeAttributesFrom(ArgDeclSpecAttrs);
7443 // Parse the declarator. This is "PrototypeContext" or
7444 // "LambdaExprParameterContext", because we must accept either
7445 // 'declarator' or 'abstract-declarator' here.
7446 Declarator ParmDeclarator(DS, ArgDeclAttrs,
7447 DeclaratorCtx == DeclaratorContext::RequiresExpr
7448 ? DeclaratorContext::RequiresExpr
7449 : DeclaratorCtx == DeclaratorContext::LambdaExpr
7450 ? DeclaratorContext::LambdaExprParameter
7451 : DeclaratorContext::Prototype);
7452 ParseDeclarator(ParmDeclarator);
7454 if (ThisLoc.isValid())
7455 ParmDeclarator.SetRangeBegin(ThisLoc);
7457 // Parse GNU attributes, if present.
7458 MaybeParseGNUAttributes(ParmDeclarator);
7459 if (getLangOpts().HLSL)
7460 MaybeParseHLSLSemantics(DS.getAttributes());
7462 if (Tok.is(tok::kw_requires)) {
7463 // User tried to define a requires clause in a parameter declaration,
7464 // which is surely not a function declaration.
7465 // void f(int (*g)(int, int) requires true);
7466 Diag(Tok,
7467 diag::err_requires_clause_on_declarator_not_declaring_a_function);
7468 ConsumeToken();
7469 Actions.CorrectDelayedTyposInExpr(
7470 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
7473 // Remember this parsed parameter in ParamInfo.
7474 IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
7476 // DefArgToks is used when the parsing of default arguments needs
7477 // to be delayed.
7478 std::unique_ptr<CachedTokens> DefArgToks;
7480 // If no parameter was specified, verify that *something* was specified,
7481 // otherwise we have a missing type and identifier.
7482 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
7483 ParmDeclarator.getNumTypeObjects() == 0) {
7484 // Completely missing, emit error.
7485 Diag(DSStart, diag::err_missing_param);
7486 } else {
7487 // Otherwise, we have something. Add it and let semantic analysis try
7488 // to grok it and add the result to the ParamInfo we are building.
7490 // Last chance to recover from a misplaced ellipsis in an attempted
7491 // parameter pack declaration.
7492 if (Tok.is(tok::ellipsis) &&
7493 (NextToken().isNot(tok::r_paren) ||
7494 (!ParmDeclarator.getEllipsisLoc().isValid() &&
7495 !Actions.isUnexpandedParameterPackPermitted())) &&
7496 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
7497 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
7499 // Now we are at the point where declarator parsing is finished.
7501 // Try to catch keywords in place of the identifier in a declarator, and
7502 // in particular the common case where:
7503 // 1 identifier comes at the end of the declarator
7504 // 2 if the identifier is dropped, the declarator is valid but anonymous
7505 // (no identifier)
7506 // 3 declarator parsing succeeds, and then we have a trailing keyword,
7507 // which is never valid in a param list (e.g. missing a ',')
7508 // And we can't handle this in ParseDeclarator because in general keywords
7509 // may be allowed to follow the declarator. (And in some cases there'd be
7510 // better recovery like inserting punctuation). ParseDeclarator is just
7511 // treating this as an anonymous parameter, and fortunately at this point
7512 // we've already almost done that.
7514 // We care about case 1) where the declarator type should be known, and
7515 // the identifier should be null.
7516 if (!ParmDeclarator.isInvalidType() && !ParmDeclarator.hasName() &&
7517 Tok.isNot(tok::raw_identifier) && !Tok.isAnnotation() &&
7518 Tok.getIdentifierInfo() &&
7519 Tok.getIdentifierInfo()->isKeyword(getLangOpts())) {
7520 Diag(Tok, diag::err_keyword_as_parameter) << PP.getSpelling(Tok);
7521 // Consume the keyword.
7522 ConsumeToken();
7524 // Inform the actions module about the parameter declarator, so it gets
7525 // added to the current scope.
7526 Decl *Param =
7527 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator, ThisLoc);
7528 // Parse the default argument, if any. We parse the default
7529 // arguments in all dialects; the semantic analysis in
7530 // ActOnParamDefaultArgument will reject the default argument in
7531 // C.
7532 if (Tok.is(tok::equal)) {
7533 SourceLocation EqualLoc = Tok.getLocation();
7535 // Parse the default argument
7536 if (DeclaratorCtx == DeclaratorContext::Member) {
7537 // If we're inside a class definition, cache the tokens
7538 // corresponding to the default argument. We'll actually parse
7539 // them when we see the end of the class definition.
7540 DefArgToks.reset(new CachedTokens);
7542 SourceLocation ArgStartLoc = NextToken().getLocation();
7543 ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument);
7544 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
7545 ArgStartLoc);
7546 } else {
7547 // Consume the '='.
7548 ConsumeToken();
7550 // The argument isn't actually potentially evaluated unless it is
7551 // used.
7552 EnterExpressionEvaluationContext Eval(
7553 Actions,
7554 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
7555 Param);
7557 ExprResult DefArgResult;
7558 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
7559 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
7560 DefArgResult = ParseBraceInitializer();
7561 } else {
7562 if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
7563 Diag(Tok, diag::err_stmt_expr_in_default_arg) << 0;
7564 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
7565 /*DefaultArg=*/nullptr);
7566 // Skip the statement expression and continue parsing
7567 SkipUntil(tok::comma, StopBeforeMatch);
7568 continue;
7570 DefArgResult = ParseAssignmentExpression();
7572 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
7573 if (DefArgResult.isInvalid()) {
7574 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
7575 /*DefaultArg=*/nullptr);
7576 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
7577 } else {
7578 // Inform the actions module about the default argument
7579 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
7580 DefArgResult.get());
7585 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7586 ParmDeclarator.getIdentifierLoc(),
7587 Param, std::move(DefArgToks)));
7590 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
7591 if (!getLangOpts().CPlusPlus) {
7592 // We have ellipsis without a preceding ',', which is ill-formed
7593 // in C. Complain and provide the fix.
7594 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
7595 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7596 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
7597 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
7598 // It looks like this was supposed to be a parameter pack. Warn and
7599 // point out where the ellipsis should have gone.
7600 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
7601 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
7602 << ParmEllipsis.isValid() << ParmEllipsis;
7603 if (ParmEllipsis.isValid()) {
7604 Diag(ParmEllipsis,
7605 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
7606 } else {
7607 Diag(ParmDeclarator.getIdentifierLoc(),
7608 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
7609 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
7610 "...")
7611 << !ParmDeclarator.hasName();
7613 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
7614 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7617 // We can't have any more parameters after an ellipsis.
7618 break;
7621 // If the next token is a comma, consume it and keep reading arguments.
7622 } while (TryConsumeToken(tok::comma));
7625 /// [C90] direct-declarator '[' constant-expression[opt] ']'
7626 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
7627 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
7628 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
7629 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
7630 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
7631 /// attribute-specifier-seq[opt]
7632 void Parser::ParseBracketDeclarator(Declarator &D) {
7633 if (CheckProhibitedCXX11Attribute())
7634 return;
7636 BalancedDelimiterTracker T(*this, tok::l_square);
7637 T.consumeOpen();
7639 // C array syntax has many features, but by-far the most common is [] and [4].
7640 // This code does a fast path to handle some of the most obvious cases.
7641 if (Tok.getKind() == tok::r_square) {
7642 T.consumeClose();
7643 ParsedAttributes attrs(AttrFactory);
7644 MaybeParseCXX11Attributes(attrs);
7646 // Remember that we parsed the empty array type.
7647 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
7648 T.getOpenLocation(),
7649 T.getCloseLocation()),
7650 std::move(attrs), T.getCloseLocation());
7651 return;
7652 } else if (Tok.getKind() == tok::numeric_constant &&
7653 GetLookAheadToken(1).is(tok::r_square)) {
7654 // [4] is very common. Parse the numeric constant expression.
7655 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
7656 ConsumeToken();
7658 T.consumeClose();
7659 ParsedAttributes attrs(AttrFactory);
7660 MaybeParseCXX11Attributes(attrs);
7662 // Remember that we parsed a array type, and remember its features.
7663 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
7664 T.getOpenLocation(),
7665 T.getCloseLocation()),
7666 std::move(attrs), T.getCloseLocation());
7667 return;
7668 } else if (Tok.getKind() == tok::code_completion) {
7669 cutOffParsing();
7670 Actions.CodeCompleteBracketDeclarator(getCurScope());
7671 return;
7674 // If valid, this location is the position where we read the 'static' keyword.
7675 SourceLocation StaticLoc;
7676 TryConsumeToken(tok::kw_static, StaticLoc);
7678 // If there is a type-qualifier-list, read it now.
7679 // Type qualifiers in an array subscript are a C99 feature.
7680 DeclSpec DS(AttrFactory);
7681 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
7683 // If we haven't already read 'static', check to see if there is one after the
7684 // type-qualifier-list.
7685 if (!StaticLoc.isValid())
7686 TryConsumeToken(tok::kw_static, StaticLoc);
7688 // Handle "direct-declarator [ type-qual-list[opt] * ]".
7689 bool isStar = false;
7690 ExprResult NumElements;
7692 // Handle the case where we have '[*]' as the array size. However, a leading
7693 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
7694 // the token after the star is a ']'. Since stars in arrays are
7695 // infrequent, use of lookahead is not costly here.
7696 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
7697 ConsumeToken(); // Eat the '*'.
7699 if (StaticLoc.isValid()) {
7700 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
7701 StaticLoc = SourceLocation(); // Drop the static.
7703 isStar = true;
7704 } else if (Tok.isNot(tok::r_square)) {
7705 // Note, in C89, this production uses the constant-expr production instead
7706 // of assignment-expr. The only difference is that assignment-expr allows
7707 // things like '=' and '*='. Sema rejects these in C89 mode because they
7708 // are not i-c-e's, so we don't need to distinguish between the two here.
7710 // Parse the constant-expression or assignment-expression now (depending
7711 // on dialect).
7712 if (getLangOpts().CPlusPlus) {
7713 NumElements = ParseArrayBoundExpression();
7714 } else {
7715 EnterExpressionEvaluationContext Unevaluated(
7716 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7717 NumElements =
7718 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
7720 } else {
7721 if (StaticLoc.isValid()) {
7722 Diag(StaticLoc, diag::err_unspecified_size_with_static);
7723 StaticLoc = SourceLocation(); // Drop the static.
7727 // If there was an error parsing the assignment-expression, recover.
7728 if (NumElements.isInvalid()) {
7729 D.setInvalidType(true);
7730 // If the expression was invalid, skip it.
7731 SkipUntil(tok::r_square, StopAtSemi);
7732 return;
7735 T.consumeClose();
7737 MaybeParseCXX11Attributes(DS.getAttributes());
7739 // Remember that we parsed a array type, and remember its features.
7740 D.AddTypeInfo(
7741 DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
7742 isStar, NumElements.get(), T.getOpenLocation(),
7743 T.getCloseLocation()),
7744 std::move(DS.getAttributes()), T.getCloseLocation());
7747 /// Diagnose brackets before an identifier.
7748 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
7749 assert(Tok.is(tok::l_square) && "Missing opening bracket");
7750 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
7752 SourceLocation StartBracketLoc = Tok.getLocation();
7753 Declarator TempDeclarator(D.getDeclSpec(), ParsedAttributesView::none(),
7754 D.getContext());
7756 while (Tok.is(tok::l_square)) {
7757 ParseBracketDeclarator(TempDeclarator);
7760 // Stuff the location of the start of the brackets into the Declarator.
7761 // The diagnostics from ParseDirectDeclarator will make more sense if
7762 // they use this location instead.
7763 if (Tok.is(tok::semi))
7764 D.getName().EndLocation = StartBracketLoc;
7766 SourceLocation SuggestParenLoc = Tok.getLocation();
7768 // Now that the brackets are removed, try parsing the declarator again.
7769 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
7771 // Something went wrong parsing the brackets, in which case,
7772 // ParseBracketDeclarator has emitted an error, and we don't need to emit
7773 // one here.
7774 if (TempDeclarator.getNumTypeObjects() == 0)
7775 return;
7777 // Determine if parens will need to be suggested in the diagnostic.
7778 bool NeedParens = false;
7779 if (D.getNumTypeObjects() != 0) {
7780 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
7781 case DeclaratorChunk::Pointer:
7782 case DeclaratorChunk::Reference:
7783 case DeclaratorChunk::BlockPointer:
7784 case DeclaratorChunk::MemberPointer:
7785 case DeclaratorChunk::Pipe:
7786 NeedParens = true;
7787 break;
7788 case DeclaratorChunk::Array:
7789 case DeclaratorChunk::Function:
7790 case DeclaratorChunk::Paren:
7791 break;
7795 if (NeedParens) {
7796 // Create a DeclaratorChunk for the inserted parens.
7797 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7798 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
7799 SourceLocation());
7802 // Adding back the bracket info to the end of the Declarator.
7803 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
7804 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
7805 D.AddTypeInfo(Chunk, SourceLocation());
7808 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
7809 // If parentheses are required, always suggest them.
7810 if (!D.getIdentifier() && !NeedParens)
7811 return;
7813 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
7815 // Generate the move bracket error message.
7816 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
7817 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7819 if (NeedParens) {
7820 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7821 << getLangOpts().CPlusPlus
7822 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
7823 << FixItHint::CreateInsertion(EndLoc, ")")
7824 << FixItHint::CreateInsertionFromRange(
7825 EndLoc, CharSourceRange(BracketRange, true))
7826 << FixItHint::CreateRemoval(BracketRange);
7827 } else {
7828 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7829 << getLangOpts().CPlusPlus
7830 << FixItHint::CreateInsertionFromRange(
7831 EndLoc, CharSourceRange(BracketRange, true))
7832 << FixItHint::CreateRemoval(BracketRange);
7836 /// [GNU] typeof-specifier:
7837 /// typeof ( expressions )
7838 /// typeof ( type-name )
7839 /// [GNU/C++] typeof unary-expression
7840 /// [C23] typeof-specifier:
7841 /// typeof '(' typeof-specifier-argument ')'
7842 /// typeof_unqual '(' typeof-specifier-argument ')'
7844 /// typeof-specifier-argument:
7845 /// expression
7846 /// type-name
7848 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
7849 assert(Tok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
7850 "Not a typeof specifier");
7852 bool IsUnqual = Tok.is(tok::kw_typeof_unqual);
7853 const IdentifierInfo *II = Tok.getIdentifierInfo();
7854 if (getLangOpts().C23 && !II->getName().startswith("__"))
7855 Diag(Tok.getLocation(), diag::warn_c23_compat_keyword) << Tok.getName();
7857 Token OpTok = Tok;
7858 SourceLocation StartLoc = ConsumeToken();
7859 bool HasParens = Tok.is(tok::l_paren);
7861 EnterExpressionEvaluationContext Unevaluated(
7862 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
7863 Sema::ReuseLambdaContextDecl);
7865 bool isCastExpr;
7866 ParsedType CastTy;
7867 SourceRange CastRange;
7868 ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
7869 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
7870 if (HasParens)
7871 DS.setTypeArgumentRange(CastRange);
7873 if (CastRange.getEnd().isInvalid())
7874 // FIXME: Not accurate, the range gets one token more than it should.
7875 DS.SetRangeEnd(Tok.getLocation());
7876 else
7877 DS.SetRangeEnd(CastRange.getEnd());
7879 if (isCastExpr) {
7880 if (!CastTy) {
7881 DS.SetTypeSpecError();
7882 return;
7885 const char *PrevSpec = nullptr;
7886 unsigned DiagID;
7887 // Check for duplicate type specifiers (e.g. "int typeof(int)").
7888 if (DS.SetTypeSpecType(IsUnqual ? DeclSpec::TST_typeof_unqualType
7889 : DeclSpec::TST_typeofType,
7890 StartLoc, PrevSpec,
7891 DiagID, CastTy,
7892 Actions.getASTContext().getPrintingPolicy()))
7893 Diag(StartLoc, DiagID) << PrevSpec;
7894 return;
7897 // If we get here, the operand to the typeof was an expression.
7898 if (Operand.isInvalid()) {
7899 DS.SetTypeSpecError();
7900 return;
7903 // We might need to transform the operand if it is potentially evaluated.
7904 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
7905 if (Operand.isInvalid()) {
7906 DS.SetTypeSpecError();
7907 return;
7910 const char *PrevSpec = nullptr;
7911 unsigned DiagID;
7912 // Check for duplicate type specifiers (e.g. "int typeof(int)").
7913 if (DS.SetTypeSpecType(IsUnqual ? DeclSpec::TST_typeof_unqualExpr
7914 : DeclSpec::TST_typeofExpr,
7915 StartLoc, PrevSpec,
7916 DiagID, Operand.get(),
7917 Actions.getASTContext().getPrintingPolicy()))
7918 Diag(StartLoc, DiagID) << PrevSpec;
7921 /// [C11] atomic-specifier:
7922 /// _Atomic ( type-name )
7924 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
7925 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
7926 "Not an atomic specifier");
7928 SourceLocation StartLoc = ConsumeToken();
7929 BalancedDelimiterTracker T(*this, tok::l_paren);
7930 if (T.consumeOpen())
7931 return;
7933 TypeResult Result = ParseTypeName();
7934 if (Result.isInvalid()) {
7935 SkipUntil(tok::r_paren, StopAtSemi);
7936 return;
7939 // Match the ')'
7940 T.consumeClose();
7942 if (T.getCloseLocation().isInvalid())
7943 return;
7945 DS.setTypeArgumentRange(T.getRange());
7946 DS.SetRangeEnd(T.getCloseLocation());
7948 const char *PrevSpec = nullptr;
7949 unsigned DiagID;
7950 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
7951 DiagID, Result.get(),
7952 Actions.getASTContext().getPrintingPolicy()))
7953 Diag(StartLoc, DiagID) << PrevSpec;
7956 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
7957 /// from TryAltiVecVectorToken.
7958 bool Parser::TryAltiVecVectorTokenOutOfLine() {
7959 Token Next = NextToken();
7960 switch (Next.getKind()) {
7961 default: return false;
7962 case tok::kw_short:
7963 case tok::kw_long:
7964 case tok::kw_signed:
7965 case tok::kw_unsigned:
7966 case tok::kw_void:
7967 case tok::kw_char:
7968 case tok::kw_int:
7969 case tok::kw_float:
7970 case tok::kw_double:
7971 case tok::kw_bool:
7972 case tok::kw__Bool:
7973 case tok::kw___bool:
7974 case tok::kw___pixel:
7975 Tok.setKind(tok::kw___vector);
7976 return true;
7977 case tok::identifier:
7978 if (Next.getIdentifierInfo() == Ident_pixel) {
7979 Tok.setKind(tok::kw___vector);
7980 return true;
7982 if (Next.getIdentifierInfo() == Ident_bool ||
7983 Next.getIdentifierInfo() == Ident_Bool) {
7984 Tok.setKind(tok::kw___vector);
7985 return true;
7987 return false;
7991 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7992 const char *&PrevSpec, unsigned &DiagID,
7993 bool &isInvalid) {
7994 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
7995 if (Tok.getIdentifierInfo() == Ident_vector) {
7996 Token Next = NextToken();
7997 switch (Next.getKind()) {
7998 case tok::kw_short:
7999 case tok::kw_long:
8000 case tok::kw_signed:
8001 case tok::kw_unsigned:
8002 case tok::kw_void:
8003 case tok::kw_char:
8004 case tok::kw_int:
8005 case tok::kw_float:
8006 case tok::kw_double:
8007 case tok::kw_bool:
8008 case tok::kw__Bool:
8009 case tok::kw___bool:
8010 case tok::kw___pixel:
8011 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
8012 return true;
8013 case tok::identifier:
8014 if (Next.getIdentifierInfo() == Ident_pixel) {
8015 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
8016 return true;
8018 if (Next.getIdentifierInfo() == Ident_bool ||
8019 Next.getIdentifierInfo() == Ident_Bool) {
8020 isInvalid =
8021 DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
8022 return true;
8024 break;
8025 default:
8026 break;
8028 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
8029 DS.isTypeAltiVecVector()) {
8030 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
8031 return true;
8032 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
8033 DS.isTypeAltiVecVector()) {
8034 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
8035 return true;
8037 return false;
8040 void Parser::DiagnoseBitIntUse(const Token &Tok) {
8041 // If the token is for _ExtInt, diagnose it as being deprecated. Otherwise,
8042 // the token is about _BitInt and gets (potentially) diagnosed as use of an
8043 // extension.
8044 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
8045 "expected either an _ExtInt or _BitInt token!");
8047 SourceLocation Loc = Tok.getLocation();
8048 if (Tok.is(tok::kw__ExtInt)) {
8049 Diag(Loc, diag::warn_ext_int_deprecated)
8050 << FixItHint::CreateReplacement(Loc, "_BitInt");
8051 } else {
8052 // In C23 mode, diagnose that the use is not compatible with pre-C23 modes.
8053 // Otherwise, diagnose that the use is a Clang extension.
8054 if (getLangOpts().C23)
8055 Diag(Loc, diag::warn_c23_compat_keyword) << Tok.getName();
8056 else
8057 Diag(Loc, diag::ext_bit_int) << getLangOpts().CPlusPlus;