clang 19.0.0git
ParseDecl.cpp
Go to the documentation of this file.
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.
10//
11//===----------------------------------------------------------------------===//
12
23#include "clang/Parse/Parser.h"
26#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaCUDA.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/SmallString.h"
34#include "llvm/ADT/StringSwitch.h"
35#include <optional>
36
37using namespace clang;
38
39//===----------------------------------------------------------------------===//
40// C99 6.7: Declarations.
41//===----------------------------------------------------------------------===//
42
43/// ParseTypeName
44/// type-name: [C99 6.7.6]
45/// specifier-qualifier-list abstract-declarator[opt]
46///
47/// Called type-id in C++.
49 AccessSpecifier AS, Decl **OwnedType,
50 ParsedAttributes *Attrs) {
51 DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
52 if (DSC == DeclSpecContext::DSC_normal)
53 DSC = DeclSpecContext::DSC_type_specifier;
54
55 // Parse the common declaration-specifiers piece.
56 DeclSpec DS(AttrFactory);
57 if (Attrs)
58 DS.addAttributes(*Attrs);
59 ParseSpecifierQualifierList(DS, AS, DSC);
60 if (OwnedType)
61 *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
62
63 // Move declspec attributes to ParsedAttributes
64 if (Attrs) {
66 for (ParsedAttr &AL : DS.getAttributes()) {
67 if (AL.isDeclspecAttribute())
68 ToBeMoved.push_back(&AL);
69 }
70
71 for (ParsedAttr *AL : ToBeMoved)
72 Attrs->takeOneFrom(DS.getAttributes(), AL);
73 }
74
75 // Parse the abstract-declarator, if present.
76 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
77 ParseDeclarator(DeclaratorInfo);
78 if (Range)
79 *Range = DeclaratorInfo.getSourceRange();
80
81 if (DeclaratorInfo.isInvalidType())
82 return true;
83
84 return Actions.ActOnTypeName(DeclaratorInfo);
85}
86
87/// Normalizes an attribute name by dropping prefixed and suffixed __.
88static StringRef normalizeAttrName(StringRef Name) {
89 if (Name.size() >= 4 && Name.starts_with("__") && Name.ends_with("__"))
90 return Name.drop_front(2).drop_back(2);
91 return Name;
92}
93
94/// isAttributeLateParsed - Return true if the attribute has arguments that
95/// require late parsing.
96static bool isAttributeLateParsed(const IdentifierInfo &II) {
97#define CLANG_ATTR_LATE_PARSED_LIST
98 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
99#include "clang/Parse/AttrParserStringSwitches.inc"
100 .Default(false);
101#undef CLANG_ATTR_LATE_PARSED_LIST
102}
103
104/// Check if the a start and end source location expand to the same macro.
106 SourceLocation EndLoc) {
107 if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
108 return false;
109
111 if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
112 return false;
113
114 bool AttrStartIsInMacro =
116 bool AttrEndIsInMacro =
118 return AttrStartIsInMacro && AttrEndIsInMacro;
119}
120
121void Parser::ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
122 LateParsedAttrList *LateAttrs) {
123 bool MoreToParse;
124 do {
125 // Assume there's nothing left to parse, but if any attributes are in fact
126 // parsed, loop to ensure all specified attribute combinations are parsed.
127 MoreToParse = false;
128 if (WhichAttrKinds & PAKM_CXX11)
129 MoreToParse |= MaybeParseCXX11Attributes(Attrs);
130 if (WhichAttrKinds & PAKM_GNU)
131 MoreToParse |= MaybeParseGNUAttributes(Attrs, LateAttrs);
132 if (WhichAttrKinds & PAKM_Declspec)
133 MoreToParse |= MaybeParseMicrosoftDeclSpecs(Attrs);
134 } while (MoreToParse);
135}
136
137/// ParseGNUAttributes - Parse a non-empty attributes list.
138///
139/// [GNU] attributes:
140/// attribute
141/// attributes attribute
142///
143/// [GNU] attribute:
144/// '__attribute__' '(' '(' attribute-list ')' ')'
145///
146/// [GNU] attribute-list:
147/// attrib
148/// attribute_list ',' attrib
149///
150/// [GNU] attrib:
151/// empty
152/// attrib-name
153/// attrib-name '(' identifier ')'
154/// attrib-name '(' identifier ',' nonempty-expr-list ')'
155/// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
156///
157/// [GNU] attrib-name:
158/// identifier
159/// typespec
160/// typequal
161/// storageclass
162///
163/// Whether an attribute takes an 'identifier' is determined by the
164/// attrib-name. GCC's behavior here is not worth imitating:
165///
166/// * In C mode, if the attribute argument list starts with an identifier
167/// followed by a ',' or an ')', and the identifier doesn't resolve to
168/// a type, it is parsed as an identifier. If the attribute actually
169/// wanted an expression, it's out of luck (but it turns out that no
170/// attributes work that way, because C constant expressions are very
171/// limited).
172/// * In C++ mode, if the attribute argument list starts with an identifier,
173/// and the attribute *wants* an identifier, it is parsed as an identifier.
174/// At block scope, any additional tokens between the identifier and the
175/// ',' or ')' are ignored, otherwise they produce a parse error.
176///
177/// We follow the C++ model, but don't allow junk after the identifier.
178void Parser::ParseGNUAttributes(ParsedAttributes &Attrs,
179 LateParsedAttrList *LateAttrs, Declarator *D) {
180 assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
181
182 SourceLocation StartLoc = Tok.getLocation();
183 SourceLocation EndLoc = StartLoc;
184
185 while (Tok.is(tok::kw___attribute)) {
186 SourceLocation AttrTokLoc = ConsumeToken();
187 unsigned OldNumAttrs = Attrs.size();
188 unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
189
190 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
191 "attribute")) {
192 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
193 return;
194 }
195 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
196 SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
197 return;
198 }
199 // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
200 do {
201 // Eat preceeding commas to allow __attribute__((,,,foo))
202 while (TryConsumeToken(tok::comma))
203 ;
204
205 // Expect an identifier or declaration specifier (const, int, etc.)
206 if (Tok.isAnnotation())
207 break;
208 if (Tok.is(tok::code_completion)) {
209 cutOffParsing();
211 break;
212 }
213 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
214 if (!AttrName)
215 break;
216
217 SourceLocation AttrNameLoc = ConsumeToken();
218
219 if (Tok.isNot(tok::l_paren)) {
220 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
221 ParsedAttr::Form::GNU());
222 continue;
223 }
224
225 // Handle "parameterized" attributes
226 if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
227 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr,
228 SourceLocation(), ParsedAttr::Form::GNU(), D);
229 continue;
230 }
231
232 // Handle attributes with arguments that require late parsing.
233 LateParsedAttribute *LA =
234 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
235 LateAttrs->push_back(LA);
236
237 // Attributes in a class are parsed at the end of the class, along
238 // with other late-parsed declarations.
239 if (!ClassStack.empty() && !LateAttrs->parseSoon())
240 getCurrentClass().LateParsedDeclarations.push_back(LA);
241
242 // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
243 // recursively consumes balanced parens.
244 LA->Toks.push_back(Tok);
245 ConsumeParen();
246 // Consume everything up to and including the matching right parens.
247 ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
248
249 Token Eof;
250 Eof.startToken();
251 Eof.setLocation(Tok.getLocation());
252 LA->Toks.push_back(Eof);
253 } while (Tok.is(tok::comma));
254
255 if (ExpectAndConsume(tok::r_paren))
256 SkipUntil(tok::r_paren, StopAtSemi);
257 SourceLocation Loc = Tok.getLocation();
258 if (ExpectAndConsume(tok::r_paren))
259 SkipUntil(tok::r_paren, StopAtSemi);
260 EndLoc = Loc;
261
262 // If this was declared in a macro, attach the macro IdentifierInfo to the
263 // parsed attribute.
264 auto &SM = PP.getSourceManager();
265 if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
266 FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
267 CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
268 StringRef FoundName =
269 Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
270 IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
271
272 for (unsigned i = OldNumAttrs; i < Attrs.size(); ++i)
273 Attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
274
275 if (LateAttrs) {
276 for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
277 (*LateAttrs)[i]->MacroII = MacroII;
278 }
279 }
280 }
281
282 Attrs.Range = SourceRange(StartLoc, EndLoc);
283}
284
285/// Determine whether the given attribute has an identifier argument.
287#define CLANG_ATTR_IDENTIFIER_ARG_LIST
288 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
289#include "clang/Parse/AttrParserStringSwitches.inc"
290 .Default(false);
291#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
292}
293
294/// Determine whether the given attribute has an identifier argument.
296attributeStringLiteralListArg(const llvm::Triple &T, const IdentifierInfo &II) {
297#define CLANG_ATTR_STRING_LITERAL_ARG_LIST
298 return llvm::StringSwitch<uint32_t>(normalizeAttrName(II.getName()))
299#include "clang/Parse/AttrParserStringSwitches.inc"
300 .Default(0);
301#undef CLANG_ATTR_STRING_LITERAL_ARG_LIST
302}
303
304/// Determine whether the given attribute has a variadic identifier argument.
306#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
307 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
308#include "clang/Parse/AttrParserStringSwitches.inc"
309 .Default(false);
310#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
311}
312
313/// Determine whether the given attribute treats kw_this as an identifier.
315#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
316 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
317#include "clang/Parse/AttrParserStringSwitches.inc"
318 .Default(false);
319#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
320}
321
322/// Determine if an attribute accepts parameter packs.
324#define CLANG_ATTR_ACCEPTS_EXPR_PACK
325 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
326#include "clang/Parse/AttrParserStringSwitches.inc"
327 .Default(false);
328#undef CLANG_ATTR_ACCEPTS_EXPR_PACK
329}
330
331/// Determine whether the given attribute parses a type argument.
333#define CLANG_ATTR_TYPE_ARG_LIST
334 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
335#include "clang/Parse/AttrParserStringSwitches.inc"
336 .Default(false);
337#undef CLANG_ATTR_TYPE_ARG_LIST
338}
339
340/// Determine whether the given attribute requires parsing its arguments
341/// in an unevaluated context or not.
343#define CLANG_ATTR_ARG_CONTEXT_LIST
344 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
345#include "clang/Parse/AttrParserStringSwitches.inc"
346 .Default(false);
347#undef CLANG_ATTR_ARG_CONTEXT_LIST
348}
349
350IdentifierLoc *Parser::ParseIdentifierLoc() {
351 assert(Tok.is(tok::identifier) && "expected an identifier");
353 Tok.getLocation(),
354 Tok.getIdentifierInfo());
355 ConsumeToken();
356 return IL;
357}
358
359void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
360 SourceLocation AttrNameLoc,
361 ParsedAttributes &Attrs,
362 IdentifierInfo *ScopeName,
363 SourceLocation ScopeLoc,
364 ParsedAttr::Form Form) {
365 BalancedDelimiterTracker Parens(*this, tok::l_paren);
366 Parens.consumeOpen();
367
369 if (Tok.isNot(tok::r_paren))
370 T = ParseTypeName();
371
372 if (Parens.consumeClose())
373 return;
374
375 if (T.isInvalid())
376 return;
377
378 if (T.isUsable())
379 Attrs.addNewTypeAttr(&AttrName,
380 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
381 ScopeName, ScopeLoc, T.get(), Form);
382 else
383 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
384 ScopeName, ScopeLoc, nullptr, 0, Form);
385}
386
388Parser::ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName) {
389 if (Tok.is(tok::l_paren)) {
390 BalancedDelimiterTracker Paren(*this, tok::l_paren);
391 Paren.consumeOpen();
392 ExprResult Res = ParseUnevaluatedStringInAttribute(AttrName);
393 Paren.consumeClose();
394 return Res;
395 }
396 if (!isTokenStringLiteral()) {
397 Diag(Tok.getLocation(), diag::err_expected_string_literal)
398 << /*in attribute...*/ 4 << AttrName.getName();
399 return ExprError();
400 }
402}
403
404bool Parser::ParseAttributeArgumentList(
405 const IdentifierInfo &AttrName, SmallVectorImpl<Expr *> &Exprs,
406 ParsedAttributeArgumentsProperties ArgsProperties) {
407 bool SawError = false;
408 unsigned Arg = 0;
409 while (true) {
411 if (ArgsProperties.isStringLiteralArg(Arg)) {
412 Expr = ParseUnevaluatedStringInAttribute(AttrName);
413 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
414 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
415 Expr = ParseBraceInitializer();
416 } else {
418 }
420
421 if (Tok.is(tok::ellipsis))
422 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
423 else if (Tok.is(tok::code_completion)) {
424 // There's nothing to suggest in here as we parsed a full expression.
425 // Instead fail and propagate the error since caller might have something
426 // the suggest, e.g. signature help in function call. Note that this is
427 // performed before pushing the \p Expr, so that signature help can report
428 // current argument correctly.
429 SawError = true;
430 cutOffParsing();
431 break;
432 }
433
434 if (Expr.isInvalid()) {
435 SawError = true;
436 break;
437 }
438
439 Exprs.push_back(Expr.get());
440
441 if (Tok.isNot(tok::comma))
442 break;
443 // Move to the next argument, remember where the comma was.
444 Token Comma = Tok;
445 ConsumeToken();
446 checkPotentialAngleBracketDelimiter(Comma);
447 Arg++;
448 }
449
450 if (SawError) {
451 // Ensure typos get diagnosed when errors were encountered while parsing the
452 // expression list.
453 for (auto &E : Exprs) {
455 if (Expr.isUsable())
456 E = Expr.get();
457 }
458 }
459 return SawError;
460}
461
462unsigned Parser::ParseAttributeArgsCommon(
463 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
464 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
465 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
466 // Ignore the left paren location for now.
467 ConsumeParen();
468
469 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
470 bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
471 bool AttributeHasVariadicIdentifierArg =
473
474 // Interpret "kw_this" as an identifier if the attributed requests it.
475 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
476 Tok.setKind(tok::identifier);
477
478 ArgsVector ArgExprs;
479 if (Tok.is(tok::identifier)) {
480 // If this attribute wants an 'identifier' argument, make it so.
481 bool IsIdentifierArg = AttributeHasVariadicIdentifierArg ||
482 attributeHasIdentifierArg(*AttrName);
483 ParsedAttr::Kind AttrKind =
484 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
485
486 // If we don't know how to parse this attribute, but this is the only
487 // token in this argument, assume it's meant to be an identifier.
488 if (AttrKind == ParsedAttr::UnknownAttribute ||
489 AttrKind == ParsedAttr::IgnoredAttribute) {
490 const Token &Next = NextToken();
491 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
492 }
493
494 if (IsIdentifierArg)
495 ArgExprs.push_back(ParseIdentifierLoc());
496 }
497
498 ParsedType TheParsedType;
499 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
500 // Eat the comma.
501 if (!ArgExprs.empty())
502 ConsumeToken();
503
504 if (AttributeIsTypeArgAttr) {
505 // FIXME: Multiple type arguments are not implemented.
507 if (T.isInvalid()) {
508 SkipUntil(tok::r_paren, StopAtSemi);
509 return 0;
510 }
511 if (T.isUsable())
512 TheParsedType = T.get();
513 } else if (AttributeHasVariadicIdentifierArg) {
514 // Parse variadic identifier arg. This can either consume identifiers or
515 // expressions. Variadic identifier args do not support parameter packs
516 // because those are typically used for attributes with enumeration
517 // arguments, and those enumerations are not something the user could
518 // express via a pack.
519 do {
520 // Interpret "kw_this" as an identifier if the attributed requests it.
521 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
522 Tok.setKind(tok::identifier);
523
524 ExprResult ArgExpr;
525 if (Tok.is(tok::identifier)) {
526 ArgExprs.push_back(ParseIdentifierLoc());
527 } else {
528 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
530 Actions,
533
534 ExprResult ArgExpr(
536
537 if (ArgExpr.isInvalid()) {
538 SkipUntil(tok::r_paren, StopAtSemi);
539 return 0;
540 }
541 ArgExprs.push_back(ArgExpr.get());
542 }
543 // Eat the comma, move to the next argument
544 } while (TryConsumeToken(tok::comma));
545 } else {
546 // General case. Parse all available expressions.
547 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
549 Actions, Uneval
552
553 ExprVector ParsedExprs;
555 attributeStringLiteralListArg(getTargetInfo().getTriple(), *AttrName);
556 if (ParseAttributeArgumentList(*AttrName, ParsedExprs, ArgProperties)) {
557 SkipUntil(tok::r_paren, StopAtSemi);
558 return 0;
559 }
560
561 // Pack expansion must currently be explicitly supported by an attribute.
562 for (size_t I = 0; I < ParsedExprs.size(); ++I) {
563 if (!isa<PackExpansionExpr>(ParsedExprs[I]))
564 continue;
565
566 if (!attributeAcceptsExprPack(*AttrName)) {
567 Diag(Tok.getLocation(),
568 diag::err_attribute_argument_parm_pack_not_supported)
569 << AttrName;
570 SkipUntil(tok::r_paren, StopAtSemi);
571 return 0;
572 }
573 }
574
575 ArgExprs.insert(ArgExprs.end(), ParsedExprs.begin(), ParsedExprs.end());
576 }
577 }
578
579 SourceLocation RParen = Tok.getLocation();
580 if (!ExpectAndConsume(tok::r_paren)) {
581 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
582
583 if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
584 Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
585 ScopeName, ScopeLoc, TheParsedType, Form);
586 } else {
587 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
588 ArgExprs.data(), ArgExprs.size(), Form);
589 }
590 }
591
592 if (EndLoc)
593 *EndLoc = RParen;
594
595 return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
596}
597
598/// Parse the arguments to a parameterized GNU attribute or
599/// a C++11 attribute in "gnu" namespace.
600void Parser::ParseGNUAttributeArgs(
601 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
602 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
603 SourceLocation ScopeLoc, ParsedAttr::Form Form, Declarator *D) {
604
605 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
606
607 ParsedAttr::Kind AttrKind =
608 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
609
610 if (AttrKind == ParsedAttr::AT_Availability) {
611 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
612 ScopeLoc, Form);
613 return;
614 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
615 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
616 ScopeName, ScopeLoc, Form);
617 return;
618 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
619 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
620 ScopeName, ScopeLoc, Form);
621 return;
622 } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
623 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
624 ScopeLoc, Form);
625 return;
626 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
627 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
628 ScopeName, ScopeLoc, Form);
629 return;
630 } else if (attributeIsTypeArgAttr(*AttrName)) {
631 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, ScopeName,
632 ScopeLoc, Form);
633 return;
634 } else if (AttrKind == ParsedAttr::AT_CountedBy) {
635 ParseBoundsAttribute(*AttrName, AttrNameLoc, Attrs, ScopeName, ScopeLoc,
636 Form);
637 return;
638 }
639
640 // These may refer to the function arguments, but need to be parsed early to
641 // participate in determining whether it's a redeclaration.
642 std::optional<ParseScope> PrototypeScope;
643 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
644 D && D->isFunctionDeclarator()) {
646 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
649 for (unsigned i = 0; i != FTI.NumParams; ++i) {
650 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
652 }
653 }
654
655 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
656 ScopeLoc, Form);
657}
658
659unsigned Parser::ParseClangAttributeArgs(
660 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
661 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
662 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
663 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
664
665 ParsedAttr::Kind AttrKind =
666 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
667
668 switch (AttrKind) {
669 default:
670 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
671 ScopeName, ScopeLoc, Form);
672 case ParsedAttr::AT_ExternalSourceSymbol:
673 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
674 ScopeName, ScopeLoc, Form);
675 break;
676 case ParsedAttr::AT_Availability:
677 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
678 ScopeLoc, Form);
679 break;
680 case ParsedAttr::AT_ObjCBridgeRelated:
681 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
682 ScopeName, ScopeLoc, Form);
683 break;
684 case ParsedAttr::AT_SwiftNewType:
685 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
686 ScopeLoc, Form);
687 break;
688 case ParsedAttr::AT_TypeTagForDatatype:
689 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
690 ScopeName, ScopeLoc, Form);
691 break;
692 }
693 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
694}
695
696bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
697 SourceLocation AttrNameLoc,
698 ParsedAttributes &Attrs) {
699 unsigned ExistingAttrs = Attrs.size();
700
701 // If the attribute isn't known, we will not attempt to parse any
702 // arguments.
705 // Eat the left paren, then skip to the ending right paren.
706 ConsumeParen();
707 SkipUntil(tok::r_paren);
708 return false;
709 }
710
711 SourceLocation OpenParenLoc = Tok.getLocation();
712
713 if (AttrName->getName() == "property") {
714 // The property declspec is more complex in that it can take one or two
715 // assignment expressions as a parameter, but the lhs of the assignment
716 // must be named get or put.
717
718 BalancedDelimiterTracker T(*this, tok::l_paren);
719 T.expectAndConsume(diag::err_expected_lparen_after,
720 AttrName->getNameStart(), tok::r_paren);
721
722 enum AccessorKind {
723 AK_Invalid = -1,
724 AK_Put = 0,
725 AK_Get = 1 // indices into AccessorNames
726 };
727 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
728 bool HasInvalidAccessor = false;
729
730 // Parse the accessor specifications.
731 while (true) {
732 // Stop if this doesn't look like an accessor spec.
733 if (!Tok.is(tok::identifier)) {
734 // If the user wrote a completely empty list, use a special diagnostic.
735 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
736 AccessorNames[AK_Put] == nullptr &&
737 AccessorNames[AK_Get] == nullptr) {
738 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
739 break;
740 }
741
742 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
743 break;
744 }
745
746 AccessorKind Kind;
747 SourceLocation KindLoc = Tok.getLocation();
748 StringRef KindStr = Tok.getIdentifierInfo()->getName();
749 if (KindStr == "get") {
750 Kind = AK_Get;
751 } else if (KindStr == "put") {
752 Kind = AK_Put;
753
754 // Recover from the common mistake of using 'set' instead of 'put'.
755 } else if (KindStr == "set") {
756 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
757 << FixItHint::CreateReplacement(KindLoc, "put");
758 Kind = AK_Put;
759
760 // Handle the mistake of forgetting the accessor kind by skipping
761 // this accessor.
762 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
763 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
764 ConsumeToken();
765 HasInvalidAccessor = true;
766 goto next_property_accessor;
767
768 // Otherwise, complain about the unknown accessor kind.
769 } else {
770 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
771 HasInvalidAccessor = true;
772 Kind = AK_Invalid;
773
774 // Try to keep parsing unless it doesn't look like an accessor spec.
775 if (!NextToken().is(tok::equal))
776 break;
777 }
778
779 // Consume the identifier.
780 ConsumeToken();
781
782 // Consume the '='.
783 if (!TryConsumeToken(tok::equal)) {
784 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
785 << KindStr;
786 break;
787 }
788
789 // Expect the method name.
790 if (!Tok.is(tok::identifier)) {
791 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
792 break;
793 }
794
795 if (Kind == AK_Invalid) {
796 // Just drop invalid accessors.
797 } else if (AccessorNames[Kind] != nullptr) {
798 // Complain about the repeated accessor, ignore it, and keep parsing.
799 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
800 } else {
801 AccessorNames[Kind] = Tok.getIdentifierInfo();
802 }
803 ConsumeToken();
804
805 next_property_accessor:
806 // Keep processing accessors until we run out.
807 if (TryConsumeToken(tok::comma))
808 continue;
809
810 // If we run into the ')', stop without consuming it.
811 if (Tok.is(tok::r_paren))
812 break;
813
814 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
815 break;
816 }
817
818 // Only add the property attribute if it was well-formed.
819 if (!HasInvalidAccessor)
820 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
821 AccessorNames[AK_Get], AccessorNames[AK_Put],
822 ParsedAttr::Form::Declspec());
823 T.skipToEnd();
824 return !HasInvalidAccessor;
825 }
826
827 unsigned NumArgs =
828 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
829 SourceLocation(), ParsedAttr::Form::Declspec());
830
831 // If this attribute's args were parsed, and it was expected to have
832 // arguments but none were provided, emit a diagnostic.
833 if (ExistingAttrs < Attrs.size() && Attrs.back().getMaxArgs() && !NumArgs) {
834 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
835 return false;
836 }
837 return true;
838}
839
840/// [MS] decl-specifier:
841/// __declspec ( extended-decl-modifier-seq )
842///
843/// [MS] extended-decl-modifier-seq:
844/// extended-decl-modifier[opt]
845/// extended-decl-modifier extended-decl-modifier-seq
846void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
847 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
848 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
849
850 SourceLocation StartLoc = Tok.getLocation();
851 SourceLocation EndLoc = StartLoc;
852
853 while (Tok.is(tok::kw___declspec)) {
854 ConsumeToken();
855 BalancedDelimiterTracker T(*this, tok::l_paren);
856 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
857 tok::r_paren))
858 return;
859
860 // An empty declspec is perfectly legal and should not warn. Additionally,
861 // you can specify multiple attributes per declspec.
862 while (Tok.isNot(tok::r_paren)) {
863 // Attribute not present.
864 if (TryConsumeToken(tok::comma))
865 continue;
866
867 if (Tok.is(tok::code_completion)) {
868 cutOffParsing();
870 return;
871 }
872
873 // We expect either a well-known identifier or a generic string. Anything
874 // else is a malformed declspec.
875 bool IsString = Tok.getKind() == tok::string_literal;
876 if (!IsString && Tok.getKind() != tok::identifier &&
877 Tok.getKind() != tok::kw_restrict) {
878 Diag(Tok, diag::err_ms_declspec_type);
879 T.skipToEnd();
880 return;
881 }
882
883 IdentifierInfo *AttrName;
884 SourceLocation AttrNameLoc;
885 if (IsString) {
886 SmallString<8> StrBuffer;
887 bool Invalid = false;
888 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
889 if (Invalid) {
890 T.skipToEnd();
891 return;
892 }
893 AttrName = PP.getIdentifierInfo(Str);
894 AttrNameLoc = ConsumeStringToken();
895 } else {
896 AttrName = Tok.getIdentifierInfo();
897 AttrNameLoc = ConsumeToken();
898 }
899
900 bool AttrHandled = false;
901
902 // Parse attribute arguments.
903 if (Tok.is(tok::l_paren))
904 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
905 else if (AttrName->getName() == "property")
906 // The property attribute must have an argument list.
907 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
908 << AttrName->getName();
909
910 if (!AttrHandled)
911 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
912 ParsedAttr::Form::Declspec());
913 }
914 T.consumeClose();
915 EndLoc = T.getCloseLocation();
916 }
917
918 Attrs.Range = SourceRange(StartLoc, EndLoc);
919}
920
921void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
922 // Treat these like attributes
923 while (true) {
924 auto Kind = Tok.getKind();
925 switch (Kind) {
926 case tok::kw___fastcall:
927 case tok::kw___stdcall:
928 case tok::kw___thiscall:
929 case tok::kw___regcall:
930 case tok::kw___cdecl:
931 case tok::kw___vectorcall:
932 case tok::kw___ptr64:
933 case tok::kw___w64:
934 case tok::kw___ptr32:
935 case tok::kw___sptr:
936 case tok::kw___uptr: {
937 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
938 SourceLocation AttrNameLoc = ConsumeToken();
939 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
940 Kind);
941 break;
942 }
943 default:
944 return;
945 }
946 }
947}
948
949void Parser::ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &attrs) {
950 assert(Tok.is(tok::kw___funcref));
951 SourceLocation StartLoc = Tok.getLocation();
952 if (!getTargetInfo().getTriple().isWasm()) {
953 ConsumeToken();
954 Diag(StartLoc, diag::err_wasm_funcref_not_wasm);
955 return;
956 }
957
958 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
959 SourceLocation AttrNameLoc = ConsumeToken();
960 attrs.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
961 /*ScopeLoc=*/SourceLocation{}, /*Args=*/nullptr, /*numArgs=*/0,
962 tok::kw___funcref);
963}
964
965void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
966 SourceLocation StartLoc = Tok.getLocation();
967 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
968
969 if (EndLoc.isValid()) {
970 SourceRange Range(StartLoc, EndLoc);
971 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
972 }
973}
974
975SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
976 SourceLocation EndLoc;
977
978 while (true) {
979 switch (Tok.getKind()) {
980 case tok::kw_const:
981 case tok::kw_volatile:
982 case tok::kw___fastcall:
983 case tok::kw___stdcall:
984 case tok::kw___thiscall:
985 case tok::kw___cdecl:
986 case tok::kw___vectorcall:
987 case tok::kw___ptr32:
988 case tok::kw___ptr64:
989 case tok::kw___w64:
990 case tok::kw___unaligned:
991 case tok::kw___sptr:
992 case tok::kw___uptr:
993 EndLoc = ConsumeToken();
994 break;
995 default:
996 return EndLoc;
997 }
998 }
999}
1000
1001void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
1002 // Treat these like attributes
1003 while (Tok.is(tok::kw___pascal)) {
1004 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1005 SourceLocation AttrNameLoc = ConsumeToken();
1006 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1007 tok::kw___pascal);
1008 }
1009}
1010
1011void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
1012 // Treat these like attributes
1013 while (Tok.is(tok::kw___kernel)) {
1014 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1015 SourceLocation AttrNameLoc = ConsumeToken();
1016 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1017 tok::kw___kernel);
1018 }
1019}
1020
1021void Parser::ParseCUDAFunctionAttributes(ParsedAttributes &attrs) {
1022 while (Tok.is(tok::kw___noinline__)) {
1023 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1024 SourceLocation AttrNameLoc = ConsumeToken();
1025 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1026 tok::kw___noinline__);
1027 }
1028}
1029
1030void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
1031 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1032 SourceLocation AttrNameLoc = Tok.getLocation();
1033 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1034 Tok.getKind());
1035}
1036
1037bool Parser::isHLSLQualifier(const Token &Tok) const {
1038 return Tok.is(tok::kw_groupshared);
1039}
1040
1041void Parser::ParseHLSLQualifiers(ParsedAttributes &Attrs) {
1042 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1043 auto Kind = Tok.getKind();
1044 SourceLocation AttrNameLoc = ConsumeToken();
1045 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, Kind);
1046}
1047
1048void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
1049 // Treat these like attributes, even though they're type specifiers.
1050 while (true) {
1051 auto Kind = Tok.getKind();
1052 switch (Kind) {
1053 case tok::kw__Nonnull:
1054 case tok::kw__Nullable:
1055 case tok::kw__Nullable_result:
1056 case tok::kw__Null_unspecified: {
1057 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1058 SourceLocation AttrNameLoc = ConsumeToken();
1059 if (!getLangOpts().ObjC)
1060 Diag(AttrNameLoc, diag::ext_nullability)
1061 << AttrName;
1062 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1063 Kind);
1064 break;
1065 }
1066 default:
1067 return;
1068 }
1069 }
1070}
1071
1072static bool VersionNumberSeparator(const char Separator) {
1073 return (Separator == '.' || Separator == '_');
1074}
1075
1076/// Parse a version number.
1077///
1078/// version:
1079/// simple-integer
1080/// simple-integer '.' simple-integer
1081/// simple-integer '_' simple-integer
1082/// simple-integer '.' simple-integer '.' simple-integer
1083/// simple-integer '_' simple-integer '_' simple-integer
1084VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
1085 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
1086
1087 if (!Tok.is(tok::numeric_constant)) {
1088 Diag(Tok, diag::err_expected_version);
1089 SkipUntil(tok::comma, tok::r_paren,
1091 return VersionTuple();
1092 }
1093
1094 // Parse the major (and possibly minor and subminor) versions, which
1095 // are stored in the numeric constant. We utilize a quirk of the
1096 // lexer, which is that it handles something like 1.2.3 as a single
1097 // numeric constant, rather than two separate tokens.
1098 SmallString<512> Buffer;
1099 Buffer.resize(Tok.getLength()+1);
1100 const char *ThisTokBegin = &Buffer[0];
1101
1102 // Get the spelling of the token, which eliminates trigraphs, etc.
1103 bool Invalid = false;
1104 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1105 if (Invalid)
1106 return VersionTuple();
1107
1108 // Parse the major version.
1109 unsigned AfterMajor = 0;
1110 unsigned Major = 0;
1111 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
1112 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
1113 ++AfterMajor;
1114 }
1115
1116 if (AfterMajor == 0) {
1117 Diag(Tok, diag::err_expected_version);
1118 SkipUntil(tok::comma, tok::r_paren,
1120 return VersionTuple();
1121 }
1122
1123 if (AfterMajor == ActualLength) {
1124 ConsumeToken();
1125
1126 // We only had a single version component.
1127 if (Major == 0) {
1128 Diag(Tok, diag::err_zero_version);
1129 return VersionTuple();
1130 }
1131
1132 return VersionTuple(Major);
1133 }
1134
1135 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
1136 if (!VersionNumberSeparator(AfterMajorSeparator)
1137 || (AfterMajor + 1 == ActualLength)) {
1138 Diag(Tok, diag::err_expected_version);
1139 SkipUntil(tok::comma, tok::r_paren,
1141 return VersionTuple();
1142 }
1143
1144 // Parse the minor version.
1145 unsigned AfterMinor = AfterMajor + 1;
1146 unsigned Minor = 0;
1147 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
1148 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
1149 ++AfterMinor;
1150 }
1151
1152 if (AfterMinor == ActualLength) {
1153 ConsumeToken();
1154
1155 // We had major.minor.
1156 if (Major == 0 && Minor == 0) {
1157 Diag(Tok, diag::err_zero_version);
1158 return VersionTuple();
1159 }
1160
1161 return VersionTuple(Major, Minor);
1162 }
1163
1164 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
1165 // If what follows is not a '.' or '_', we have a problem.
1166 if (!VersionNumberSeparator(AfterMinorSeparator)) {
1167 Diag(Tok, diag::err_expected_version);
1168 SkipUntil(tok::comma, tok::r_paren,
1170 return VersionTuple();
1171 }
1172
1173 // Warn if separators, be it '.' or '_', do not match.
1174 if (AfterMajorSeparator != AfterMinorSeparator)
1175 Diag(Tok, diag::warn_expected_consistent_version_separator);
1176
1177 // Parse the subminor version.
1178 unsigned AfterSubminor = AfterMinor + 1;
1179 unsigned Subminor = 0;
1180 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
1181 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
1182 ++AfterSubminor;
1183 }
1184
1185 if (AfterSubminor != ActualLength) {
1186 Diag(Tok, diag::err_expected_version);
1187 SkipUntil(tok::comma, tok::r_paren,
1189 return VersionTuple();
1190 }
1191 ConsumeToken();
1192 return VersionTuple(Major, Minor, Subminor);
1193}
1194
1195/// Parse the contents of the "availability" attribute.
1196///
1197/// availability-attribute:
1198/// 'availability' '(' platform ',' opt-strict version-arg-list,
1199/// opt-replacement, opt-message')'
1200///
1201/// platform:
1202/// identifier
1203///
1204/// opt-strict:
1205/// 'strict' ','
1206///
1207/// version-arg-list:
1208/// version-arg
1209/// version-arg ',' version-arg-list
1210///
1211/// version-arg:
1212/// 'introduced' '=' version
1213/// 'deprecated' '=' version
1214/// 'obsoleted' = version
1215/// 'unavailable'
1216/// opt-replacement:
1217/// 'replacement' '=' <string>
1218/// opt-message:
1219/// 'message' '=' <string>
1220void Parser::ParseAvailabilityAttribute(
1221 IdentifierInfo &Availability, SourceLocation AvailabilityLoc,
1222 ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName,
1223 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1224 enum { Introduced, Deprecated, Obsoleted, Unknown };
1225 AvailabilityChange Changes[Unknown];
1226 ExprResult MessageExpr, ReplacementExpr;
1227
1228 // Opening '('.
1229 BalancedDelimiterTracker T(*this, tok::l_paren);
1230 if (T.consumeOpen()) {
1231 Diag(Tok, diag::err_expected) << tok::l_paren;
1232 return;
1233 }
1234
1235 // Parse the platform name.
1236 if (Tok.isNot(tok::identifier)) {
1237 Diag(Tok, diag::err_availability_expected_platform);
1238 SkipUntil(tok::r_paren, StopAtSemi);
1239 return;
1240 }
1241 IdentifierLoc *Platform = ParseIdentifierLoc();
1242 if (const IdentifierInfo *const Ident = Platform->Ident) {
1243 // Disallow xrOS for availability attributes.
1244 if (Ident->getName().contains("xrOS") || Ident->getName().contains("xros"))
1245 Diag(Platform->Loc, diag::warn_availability_unknown_platform) << Ident;
1246 // Canonicalize platform name from "macosx" to "macos".
1247 else if (Ident->getName() == "macosx")
1248 Platform->Ident = PP.getIdentifierInfo("macos");
1249 // Canonicalize platform name from "macosx_app_extension" to
1250 // "macos_app_extension".
1251 else if (Ident->getName() == "macosx_app_extension")
1252 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1253 else
1254 Platform->Ident = PP.getIdentifierInfo(
1255 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1256 }
1257
1258 // Parse the ',' following the platform name.
1259 if (ExpectAndConsume(tok::comma)) {
1260 SkipUntil(tok::r_paren, StopAtSemi);
1261 return;
1262 }
1263
1264 // If we haven't grabbed the pointers for the identifiers
1265 // "introduced", "deprecated", and "obsoleted", do so now.
1266 if (!Ident_introduced) {
1267 Ident_introduced = PP.getIdentifierInfo("introduced");
1268 Ident_deprecated = PP.getIdentifierInfo("deprecated");
1269 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1270 Ident_unavailable = PP.getIdentifierInfo("unavailable");
1271 Ident_message = PP.getIdentifierInfo("message");
1272 Ident_strict = PP.getIdentifierInfo("strict");
1273 Ident_replacement = PP.getIdentifierInfo("replacement");
1274 }
1275
1276 // Parse the optional "strict", the optional "replacement" and the set of
1277 // introductions/deprecations/removals.
1278 SourceLocation UnavailableLoc, StrictLoc;
1279 do {
1280 if (Tok.isNot(tok::identifier)) {
1281 Diag(Tok, diag::err_availability_expected_change);
1282 SkipUntil(tok::r_paren, StopAtSemi);
1283 return;
1284 }
1285 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1286 SourceLocation KeywordLoc = ConsumeToken();
1287
1288 if (Keyword == Ident_strict) {
1289 if (StrictLoc.isValid()) {
1290 Diag(KeywordLoc, diag::err_availability_redundant)
1291 << Keyword << SourceRange(StrictLoc);
1292 }
1293 StrictLoc = KeywordLoc;
1294 continue;
1295 }
1296
1297 if (Keyword == Ident_unavailable) {
1298 if (UnavailableLoc.isValid()) {
1299 Diag(KeywordLoc, diag::err_availability_redundant)
1300 << Keyword << SourceRange(UnavailableLoc);
1301 }
1302 UnavailableLoc = KeywordLoc;
1303 continue;
1304 }
1305
1306 if (Keyword == Ident_deprecated && Platform->Ident &&
1307 Platform->Ident->isStr("swift")) {
1308 // For swift, we deprecate for all versions.
1309 if (Changes[Deprecated].KeywordLoc.isValid()) {
1310 Diag(KeywordLoc, diag::err_availability_redundant)
1311 << Keyword
1312 << SourceRange(Changes[Deprecated].KeywordLoc);
1313 }
1314
1315 Changes[Deprecated].KeywordLoc = KeywordLoc;
1316 // Use a fake version here.
1317 Changes[Deprecated].Version = VersionTuple(1);
1318 continue;
1319 }
1320
1321 if (Tok.isNot(tok::equal)) {
1322 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1323 SkipUntil(tok::r_paren, StopAtSemi);
1324 return;
1325 }
1326 ConsumeToken();
1327 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1328 if (!isTokenStringLiteral()) {
1329 Diag(Tok, diag::err_expected_string_literal)
1330 << /*Source='availability attribute'*/2;
1331 SkipUntil(tok::r_paren, StopAtSemi);
1332 return;
1333 }
1334 if (Keyword == Ident_message) {
1336 break;
1337 } else {
1338 ReplacementExpr = ParseUnevaluatedStringLiteralExpression();
1339 continue;
1340 }
1341 }
1342
1343 // Special handling of 'NA' only when applied to introduced or
1344 // deprecated.
1345 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1346 Tok.is(tok::identifier)) {
1348 if (NA->getName() == "NA") {
1349 ConsumeToken();
1350 if (Keyword == Ident_introduced)
1351 UnavailableLoc = KeywordLoc;
1352 continue;
1353 }
1354 }
1355
1356 SourceRange VersionRange;
1357 VersionTuple Version = ParseVersionTuple(VersionRange);
1358
1359 if (Version.empty()) {
1360 SkipUntil(tok::r_paren, StopAtSemi);
1361 return;
1362 }
1363
1364 unsigned Index;
1365 if (Keyword == Ident_introduced)
1366 Index = Introduced;
1367 else if (Keyword == Ident_deprecated)
1368 Index = Deprecated;
1369 else if (Keyword == Ident_obsoleted)
1370 Index = Obsoleted;
1371 else
1372 Index = Unknown;
1373
1374 if (Index < Unknown) {
1375 if (!Changes[Index].KeywordLoc.isInvalid()) {
1376 Diag(KeywordLoc, diag::err_availability_redundant)
1377 << Keyword
1378 << SourceRange(Changes[Index].KeywordLoc,
1379 Changes[Index].VersionRange.getEnd());
1380 }
1381
1382 Changes[Index].KeywordLoc = KeywordLoc;
1383 Changes[Index].Version = Version;
1384 Changes[Index].VersionRange = VersionRange;
1385 } else {
1386 Diag(KeywordLoc, diag::err_availability_unknown_change)
1387 << Keyword << VersionRange;
1388 }
1389
1390 } while (TryConsumeToken(tok::comma));
1391
1392 // Closing ')'.
1393 if (T.consumeClose())
1394 return;
1395
1396 if (endLoc)
1397 *endLoc = T.getCloseLocation();
1398
1399 // The 'unavailable' availability cannot be combined with any other
1400 // availability changes. Make sure that hasn't happened.
1401 if (UnavailableLoc.isValid()) {
1402 bool Complained = false;
1403 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1404 if (Changes[Index].KeywordLoc.isValid()) {
1405 if (!Complained) {
1406 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1407 << SourceRange(Changes[Index].KeywordLoc,
1408 Changes[Index].VersionRange.getEnd());
1409 Complained = true;
1410 }
1411
1412 // Clear out the availability.
1413 Changes[Index] = AvailabilityChange();
1414 }
1415 }
1416 }
1417
1418 // Record this attribute
1419 attrs.addNew(&Availability,
1420 SourceRange(AvailabilityLoc, T.getCloseLocation()), ScopeName,
1421 ScopeLoc, Platform, Changes[Introduced], Changes[Deprecated],
1422 Changes[Obsoleted], UnavailableLoc, MessageExpr.get(), Form,
1423 StrictLoc, ReplacementExpr.get());
1424}
1425
1426/// Parse the contents of the "external_source_symbol" attribute.
1427///
1428/// external-source-symbol-attribute:
1429/// 'external_source_symbol' '(' keyword-arg-list ')'
1430///
1431/// keyword-arg-list:
1432/// keyword-arg
1433/// keyword-arg ',' keyword-arg-list
1434///
1435/// keyword-arg:
1436/// 'language' '=' <string>
1437/// 'defined_in' '=' <string>
1438/// 'USR' '=' <string>
1439/// 'generated_declaration'
1440void Parser::ParseExternalSourceSymbolAttribute(
1441 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1442 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1443 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1444 // Opening '('.
1445 BalancedDelimiterTracker T(*this, tok::l_paren);
1446 if (T.expectAndConsume())
1447 return;
1448
1449 // Initialize the pointers for the keyword identifiers when required.
1450 if (!Ident_language) {
1451 Ident_language = PP.getIdentifierInfo("language");
1452 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1453 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1454 Ident_USR = PP.getIdentifierInfo("USR");
1455 }
1456
1458 bool HasLanguage = false;
1459 ExprResult DefinedInExpr;
1460 bool HasDefinedIn = false;
1461 IdentifierLoc *GeneratedDeclaration = nullptr;
1462 ExprResult USR;
1463 bool HasUSR = false;
1464
1465 // Parse the language/defined_in/generated_declaration keywords
1466 do {
1467 if (Tok.isNot(tok::identifier)) {
1468 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1469 SkipUntil(tok::r_paren, StopAtSemi);
1470 return;
1471 }
1472
1473 SourceLocation KeywordLoc = Tok.getLocation();
1474 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1475 if (Keyword == Ident_generated_declaration) {
1476 if (GeneratedDeclaration) {
1477 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1478 SkipUntil(tok::r_paren, StopAtSemi);
1479 return;
1480 }
1481 GeneratedDeclaration = ParseIdentifierLoc();
1482 continue;
1483 }
1484
1485 if (Keyword != Ident_language && Keyword != Ident_defined_in &&
1486 Keyword != Ident_USR) {
1487 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1488 SkipUntil(tok::r_paren, StopAtSemi);
1489 return;
1490 }
1491
1492 ConsumeToken();
1493 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1494 Keyword->getName())) {
1495 SkipUntil(tok::r_paren, StopAtSemi);
1496 return;
1497 }
1498
1499 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn,
1500 HadUSR = HasUSR;
1501 if (Keyword == Ident_language)
1502 HasLanguage = true;
1503 else if (Keyword == Ident_USR)
1504 HasUSR = true;
1505 else
1506 HasDefinedIn = true;
1507
1508 if (!isTokenStringLiteral()) {
1509 Diag(Tok, diag::err_expected_string_literal)
1510 << /*Source='external_source_symbol attribute'*/ 3
1511 << /*language | source container | USR*/ (
1512 Keyword == Ident_language
1513 ? 0
1514 : (Keyword == Ident_defined_in ? 1 : 2));
1515 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1516 continue;
1517 }
1518 if (Keyword == Ident_language) {
1519 if (HadLanguage) {
1520 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1521 << Keyword;
1523 continue;
1524 }
1526 } else if (Keyword == Ident_USR) {
1527 if (HadUSR) {
1528 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1529 << Keyword;
1531 continue;
1532 }
1534 } else {
1535 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1536 if (HadDefinedIn) {
1537 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1538 << Keyword;
1540 continue;
1541 }
1543 }
1544 } while (TryConsumeToken(tok::comma));
1545
1546 // Closing ')'.
1547 if (T.consumeClose())
1548 return;
1549 if (EndLoc)
1550 *EndLoc = T.getCloseLocation();
1551
1552 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(), GeneratedDeclaration,
1553 USR.get()};
1554 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1555 ScopeName, ScopeLoc, Args, std::size(Args), Form);
1556}
1557
1558/// Parse the contents of the "objc_bridge_related" attribute.
1559/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1560/// related_class:
1561/// Identifier
1562///
1563/// opt-class_method:
1564/// Identifier: | <empty>
1565///
1566/// opt-instance_method:
1567/// Identifier | <empty>
1568///
1569void Parser::ParseObjCBridgeRelatedAttribute(
1570 IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc,
1571 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1572 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1573 // Opening '('.
1574 BalancedDelimiterTracker T(*this, tok::l_paren);
1575 if (T.consumeOpen()) {
1576 Diag(Tok, diag::err_expected) << tok::l_paren;
1577 return;
1578 }
1579
1580 // Parse the related class name.
1581 if (Tok.isNot(tok::identifier)) {
1582 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1583 SkipUntil(tok::r_paren, StopAtSemi);
1584 return;
1585 }
1586 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1587 if (ExpectAndConsume(tok::comma)) {
1588 SkipUntil(tok::r_paren, StopAtSemi);
1589 return;
1590 }
1591
1592 // Parse class method name. It's non-optional in the sense that a trailing
1593 // comma is required, but it can be the empty string, and then we record a
1594 // nullptr.
1595 IdentifierLoc *ClassMethod = nullptr;
1596 if (Tok.is(tok::identifier)) {
1597 ClassMethod = ParseIdentifierLoc();
1598 if (!TryConsumeToken(tok::colon)) {
1599 Diag(Tok, diag::err_objcbridge_related_selector_name);
1600 SkipUntil(tok::r_paren, StopAtSemi);
1601 return;
1602 }
1603 }
1604 if (!TryConsumeToken(tok::comma)) {
1605 if (Tok.is(tok::colon))
1606 Diag(Tok, diag::err_objcbridge_related_selector_name);
1607 else
1608 Diag(Tok, diag::err_expected) << tok::comma;
1609 SkipUntil(tok::r_paren, StopAtSemi);
1610 return;
1611 }
1612
1613 // Parse instance method name. Also non-optional but empty string is
1614 // permitted.
1615 IdentifierLoc *InstanceMethod = nullptr;
1616 if (Tok.is(tok::identifier))
1617 InstanceMethod = ParseIdentifierLoc();
1618 else if (Tok.isNot(tok::r_paren)) {
1619 Diag(Tok, diag::err_expected) << tok::r_paren;
1620 SkipUntil(tok::r_paren, StopAtSemi);
1621 return;
1622 }
1623
1624 // Closing ')'.
1625 if (T.consumeClose())
1626 return;
1627
1628 if (EndLoc)
1629 *EndLoc = T.getCloseLocation();
1630
1631 // Record this attribute
1632 Attrs.addNew(&ObjCBridgeRelated,
1633 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1634 ScopeName, ScopeLoc, RelatedClass, ClassMethod, InstanceMethod,
1635 Form);
1636}
1637
1638void Parser::ParseSwiftNewTypeAttribute(
1639 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1640 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1641 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1642 BalancedDelimiterTracker T(*this, tok::l_paren);
1643
1644 // Opening '('
1645 if (T.consumeOpen()) {
1646 Diag(Tok, diag::err_expected) << tok::l_paren;
1647 return;
1648 }
1649
1650 if (Tok.is(tok::r_paren)) {
1651 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1652 T.consumeClose();
1653 return;
1654 }
1655 if (Tok.isNot(tok::kw_struct) && Tok.isNot(tok::kw_enum)) {
1656 Diag(Tok, diag::warn_attribute_type_not_supported)
1657 << &AttrName << Tok.getIdentifierInfo();
1658 if (!isTokenSpecial())
1659 ConsumeToken();
1660 T.consumeClose();
1661 return;
1662 }
1663
1664 auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1665 Tok.getIdentifierInfo());
1666 ConsumeToken();
1667
1668 // Closing ')'
1669 if (T.consumeClose())
1670 return;
1671 if (EndLoc)
1672 *EndLoc = T.getCloseLocation();
1673
1674 ArgsUnion Args[] = {SwiftType};
1675 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
1676 ScopeName, ScopeLoc, Args, std::size(Args), Form);
1677}
1678
1679void Parser::ParseTypeTagForDatatypeAttribute(
1680 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1681 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1682 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1683 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1684
1685 BalancedDelimiterTracker T(*this, tok::l_paren);
1686 T.consumeOpen();
1687
1688 if (Tok.isNot(tok::identifier)) {
1689 Diag(Tok, diag::err_expected) << tok::identifier;
1690 T.skipToEnd();
1691 return;
1692 }
1693 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1694
1695 if (ExpectAndConsume(tok::comma)) {
1696 T.skipToEnd();
1697 return;
1698 }
1699
1700 SourceRange MatchingCTypeRange;
1701 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1702 if (MatchingCType.isInvalid()) {
1703 T.skipToEnd();
1704 return;
1705 }
1706
1707 bool LayoutCompatible = false;
1708 bool MustBeNull = false;
1709 while (TryConsumeToken(tok::comma)) {
1710 if (Tok.isNot(tok::identifier)) {
1711 Diag(Tok, diag::err_expected) << tok::identifier;
1712 T.skipToEnd();
1713 return;
1714 }
1715 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1716 if (Flag->isStr("layout_compatible"))
1717 LayoutCompatible = true;
1718 else if (Flag->isStr("must_be_null"))
1719 MustBeNull = true;
1720 else {
1721 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1722 T.skipToEnd();
1723 return;
1724 }
1725 ConsumeToken(); // consume flag
1726 }
1727
1728 if (!T.consumeClose()) {
1729 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1730 ArgumentKind, MatchingCType.get(),
1731 LayoutCompatible, MustBeNull, Form);
1732 }
1733
1734 if (EndLoc)
1735 *EndLoc = T.getCloseLocation();
1736}
1737
1738/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1739/// of a C++11 attribute-specifier in a location where an attribute is not
1740/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1741/// situation.
1742///
1743/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1744/// this doesn't appear to actually be an attribute-specifier, and the caller
1745/// should try to parse it.
1746bool Parser::DiagnoseProhibitedCXX11Attribute() {
1747 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1748
1749 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1750 case CAK_NotAttributeSpecifier:
1751 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1752 return false;
1753
1754 case CAK_InvalidAttributeSpecifier:
1755 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1756 return false;
1757
1758 case CAK_AttributeSpecifier:
1759 // Parse and discard the attributes.
1760 SourceLocation BeginLoc = ConsumeBracket();
1761 ConsumeBracket();
1762 SkipUntil(tok::r_square);
1763 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1764 SourceLocation EndLoc = ConsumeBracket();
1765 Diag(BeginLoc, diag::err_attributes_not_allowed)
1766 << SourceRange(BeginLoc, EndLoc);
1767 return true;
1768 }
1769 llvm_unreachable("All cases handled above.");
1770}
1771
1772/// We have found the opening square brackets of a C++11
1773/// attribute-specifier in a location where an attribute is not permitted, but
1774/// we know where the attributes ought to be written. Parse them anyway, and
1775/// provide a fixit moving them to the right place.
1776void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
1777 SourceLocation CorrectLocation) {
1778 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1779 Tok.is(tok::kw_alignas) || Tok.isRegularKeywordAttribute());
1780
1781 // Consume the attributes.
1782 auto Keyword =
1783 Tok.isRegularKeywordAttribute() ? Tok.getIdentifierInfo() : nullptr;
1784 SourceLocation Loc = Tok.getLocation();
1785 ParseCXX11Attributes(Attrs);
1786 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1787 // FIXME: use err_attributes_misplaced
1788 (Keyword ? Diag(Loc, diag::err_keyword_not_allowed) << Keyword
1789 : Diag(Loc, diag::err_attributes_not_allowed))
1790 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1791 << FixItHint::CreateRemoval(AttrRange);
1792}
1793
1794void Parser::DiagnoseProhibitedAttributes(
1795 const ParsedAttributesView &Attrs, const SourceLocation CorrectLocation) {
1796 auto *FirstAttr = Attrs.empty() ? nullptr : &Attrs.front();
1797 if (CorrectLocation.isValid()) {
1798 CharSourceRange AttrRange(Attrs.Range, true);
1799 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1800 ? Diag(CorrectLocation, diag::err_keyword_misplaced) << FirstAttr
1801 : Diag(CorrectLocation, diag::err_attributes_misplaced))
1802 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1803 << FixItHint::CreateRemoval(AttrRange);
1804 } else {
1805 const SourceRange &Range = Attrs.Range;
1806 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1807 ? Diag(Range.getBegin(), diag::err_keyword_not_allowed) << FirstAttr
1808 : Diag(Range.getBegin(), diag::err_attributes_not_allowed))
1809 << Range;
1810 }
1811}
1812
1813void Parser::ProhibitCXX11Attributes(ParsedAttributes &Attrs,
1814 unsigned AttrDiagID,
1815 unsigned KeywordDiagID,
1816 bool DiagnoseEmptyAttrs,
1817 bool WarnOnUnknownAttrs) {
1818
1819 if (DiagnoseEmptyAttrs && Attrs.empty() && Attrs.Range.isValid()) {
1820 // An attribute list has been parsed, but it was empty.
1821 // This is the case for [[]].
1822 const auto &LangOpts = getLangOpts();
1823 auto &SM = PP.getSourceManager();
1824 Token FirstLSquare;
1825 Lexer::getRawToken(Attrs.Range.getBegin(), FirstLSquare, SM, LangOpts);
1826
1827 if (FirstLSquare.is(tok::l_square)) {
1828 std::optional<Token> SecondLSquare =
1829 Lexer::findNextToken(FirstLSquare.getLocation(), SM, LangOpts);
1830
1831 if (SecondLSquare && SecondLSquare->is(tok::l_square)) {
1832 // The attribute range starts with [[, but is empty. So this must
1833 // be [[]], which we are supposed to diagnose because
1834 // DiagnoseEmptyAttrs is true.
1835 Diag(Attrs.Range.getBegin(), AttrDiagID) << Attrs.Range;
1836 return;
1837 }
1838 }
1839 }
1840
1841 for (const ParsedAttr &AL : Attrs) {
1842 if (AL.isRegularKeywordAttribute()) {
1843 Diag(AL.getLoc(), KeywordDiagID) << AL;
1844 AL.setInvalid();
1845 continue;
1846 }
1847 if (!AL.isStandardAttributeSyntax())
1848 continue;
1849 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
1850 if (WarnOnUnknownAttrs)
1851 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1852 << AL << AL.getRange();
1853 } else {
1854 Diag(AL.getLoc(), AttrDiagID) << AL;
1855 AL.setInvalid();
1856 }
1857 }
1858}
1859
1860void Parser::DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs) {
1861 for (const ParsedAttr &PA : Attrs) {
1862 if (PA.isStandardAttributeSyntax() || PA.isRegularKeywordAttribute())
1863 Diag(PA.getLoc(), diag::ext_cxx11_attr_placement)
1864 << PA << PA.isRegularKeywordAttribute() << PA.getRange();
1865 }
1866}
1867
1868// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1869// applies to var, not the type Foo.
1870// As an exception to the rule, __declspec(align(...)) before the
1871// class-key affects the type instead of the variable.
1872// Also, Microsoft-style [attributes] seem to affect the type instead of the
1873// variable.
1874// This function moves attributes that should apply to the type off DS to Attrs.
1875void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs,
1876 DeclSpec &DS,
1877 Sema::TagUseKind TUK) {
1878 if (TUK == Sema::TUK_Reference)
1879 return;
1880
1882
1883 for (ParsedAttr &AL : DS.getAttributes()) {
1884 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1885 AL.isDeclspecAttribute()) ||
1886 AL.isMicrosoftAttribute())
1887 ToBeMoved.push_back(&AL);
1888 }
1889
1890 for (ParsedAttr *AL : ToBeMoved) {
1891 DS.getAttributes().remove(AL);
1892 Attrs.addAtEnd(AL);
1893 }
1894}
1895
1896/// ParseDeclaration - Parse a full 'declaration', which consists of
1897/// declaration-specifiers, some number of declarators, and a semicolon.
1898/// 'Context' should be a DeclaratorContext value. This returns the
1899/// location of the semicolon in DeclEnd.
1900///
1901/// declaration: [C99 6.7]
1902/// block-declaration ->
1903/// simple-declaration
1904/// others [FIXME]
1905/// [C++] template-declaration
1906/// [C++] namespace-definition
1907/// [C++] using-directive
1908/// [C++] using-declaration
1909/// [C++11/C11] static_assert-declaration
1910/// others... [FIXME]
1911///
1912Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
1913 SourceLocation &DeclEnd,
1914 ParsedAttributes &DeclAttrs,
1915 ParsedAttributes &DeclSpecAttrs,
1916 SourceLocation *DeclSpecStart) {
1917 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1918 // Must temporarily exit the objective-c container scope for
1919 // parsing c none objective-c decls.
1920 ObjCDeclContextSwitch ObjCDC(*this);
1921
1922 Decl *SingleDecl = nullptr;
1923 switch (Tok.getKind()) {
1924 case tok::kw_template:
1925 case tok::kw_export:
1926 ProhibitAttributes(DeclAttrs);
1927 ProhibitAttributes(DeclSpecAttrs);
1928 return ParseDeclarationStartingWithTemplate(Context, DeclEnd, DeclAttrs);
1929 case tok::kw_inline:
1930 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1931 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1932 ProhibitAttributes(DeclAttrs);
1933 ProhibitAttributes(DeclSpecAttrs);
1934 SourceLocation InlineLoc = ConsumeToken();
1935 return ParseNamespace(Context, DeclEnd, InlineLoc);
1936 }
1937 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1938 true, nullptr, DeclSpecStart);
1939
1940 case tok::kw_cbuffer:
1941 case tok::kw_tbuffer:
1942 SingleDecl = ParseHLSLBuffer(DeclEnd);
1943 break;
1944 case tok::kw_namespace:
1945 ProhibitAttributes(DeclAttrs);
1946 ProhibitAttributes(DeclSpecAttrs);
1947 return ParseNamespace(Context, DeclEnd);
1948 case tok::kw_using: {
1949 ParsedAttributes Attrs(AttrFactory);
1950 takeAndConcatenateAttrs(DeclAttrs, DeclSpecAttrs, Attrs);
1951 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1952 DeclEnd, Attrs);
1953 }
1954 case tok::kw_static_assert:
1955 case tok::kw__Static_assert:
1956 ProhibitAttributes(DeclAttrs);
1957 ProhibitAttributes(DeclSpecAttrs);
1958 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1959 break;
1960 default:
1961 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1962 true, nullptr, DeclSpecStart);
1963 }
1964
1965 // This routine returns a DeclGroup, if the thing we parsed only contains a
1966 // single decl, convert it now.
1967 return Actions.ConvertDeclToDeclGroup(SingleDecl);
1968}
1969
1970/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1971/// declaration-specifiers init-declarator-list[opt] ';'
1972/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1973/// init-declarator-list ';'
1974///[C90/C++]init-declarator-list ';' [TODO]
1975/// [OMP] threadprivate-directive
1976/// [OMP] allocate-directive [TODO]
1977///
1978/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1979/// attribute-specifier-seq[opt] type-specifier-seq declarator
1980///
1981/// If RequireSemi is false, this does not check for a ';' at the end of the
1982/// declaration. If it is true, it checks for and eats it.
1983///
1984/// If FRI is non-null, we might be parsing a for-range-declaration instead
1985/// of a simple-declaration. If we find that we are, we also parse the
1986/// for-range-initializer, and place it here.
1987///
1988/// DeclSpecStart is used when decl-specifiers are parsed before parsing
1989/// the Declaration. The SourceLocation for this Decl is set to
1990/// DeclSpecStart if DeclSpecStart is non-null.
1991Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1992 DeclaratorContext Context, SourceLocation &DeclEnd,
1993 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
1994 bool RequireSemi, ForRangeInit *FRI, SourceLocation *DeclSpecStart) {
1995 // Need to retain these for diagnostics before we add them to the DeclSepc.
1996 ParsedAttributesView OriginalDeclSpecAttrs;
1997 OriginalDeclSpecAttrs.addAll(DeclSpecAttrs.begin(), DeclSpecAttrs.end());
1998 OriginalDeclSpecAttrs.Range = DeclSpecAttrs.Range;
1999
2000 // Parse the common declaration-specifiers piece.
2001 ParsingDeclSpec DS(*this);
2002 DS.takeAttributesFrom(DeclSpecAttrs);
2003
2004 ParsedTemplateInfo TemplateInfo;
2005 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
2006 ParseDeclarationSpecifiers(DS, TemplateInfo, AS_none, DSContext);
2007
2008 // If we had a free-standing type definition with a missing semicolon, we
2009 // may get this far before the problem becomes obvious.
2010 if (DS.hasTagDefinition() &&
2011 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
2012 return nullptr;
2013
2014 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
2015 // declaration-specifiers init-declarator-list[opt] ';'
2016 if (Tok.is(tok::semi)) {
2017 ProhibitAttributes(DeclAttrs);
2018 DeclEnd = Tok.getLocation();
2019 if (RequireSemi) ConsumeToken();
2020 RecordDecl *AnonRecord = nullptr;
2021 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2022 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
2023 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
2024 DS.complete(TheDecl);
2025 if (AnonRecord) {
2026 Decl* decls[] = {AnonRecord, TheDecl};
2027 return Actions.BuildDeclaratorGroup(decls);
2028 }
2029 return Actions.ConvertDeclToDeclGroup(TheDecl);
2030 }
2031
2032 if (DS.hasTagDefinition())
2034
2035 if (DeclSpecStart)
2036 DS.SetRangeStart(*DeclSpecStart);
2037
2038 return ParseDeclGroup(DS, Context, DeclAttrs, TemplateInfo, &DeclEnd, FRI);
2039}
2040
2041/// Returns true if this might be the start of a declarator, or a common typo
2042/// for a declarator.
2043bool Parser::MightBeDeclarator(DeclaratorContext Context) {
2044 switch (Tok.getKind()) {
2045 case tok::annot_cxxscope:
2046 case tok::annot_template_id:
2047 case tok::caret:
2048 case tok::code_completion:
2049 case tok::coloncolon:
2050 case tok::ellipsis:
2051 case tok::kw___attribute:
2052 case tok::kw_operator:
2053 case tok::l_paren:
2054 case tok::star:
2055 return true;
2056
2057 case tok::amp:
2058 case tok::ampamp:
2059 return getLangOpts().CPlusPlus;
2060
2061 case tok::l_square: // Might be an attribute on an unnamed bit-field.
2062 return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
2063 NextToken().is(tok::l_square);
2064
2065 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
2066 return Context == DeclaratorContext::Member || getLangOpts().CPlusPlus;
2067
2068 case tok::identifier:
2069 switch (NextToken().getKind()) {
2070 case tok::code_completion:
2071 case tok::coloncolon:
2072 case tok::comma:
2073 case tok::equal:
2074 case tok::equalequal: // Might be a typo for '='.
2075 case tok::kw_alignas:
2076 case tok::kw_asm:
2077 case tok::kw___attribute:
2078 case tok::l_brace:
2079 case tok::l_paren:
2080 case tok::l_square:
2081 case tok::less:
2082 case tok::r_brace:
2083 case tok::r_paren:
2084 case tok::r_square:
2085 case tok::semi:
2086 return true;
2087
2088 case tok::colon:
2089 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
2090 // and in block scope it's probably a label. Inside a class definition,
2091 // this is a bit-field.
2092 return Context == DeclaratorContext::Member ||
2093 (getLangOpts().CPlusPlus && Context == DeclaratorContext::File);
2094
2095 case tok::identifier: // Possible virt-specifier.
2096 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
2097
2098 default:
2099 return Tok.isRegularKeywordAttribute();
2100 }
2101
2102 default:
2103 return Tok.isRegularKeywordAttribute();
2104 }
2105}
2106
2107/// Skip until we reach something which seems like a sensible place to pick
2108/// up parsing after a malformed declaration. This will sometimes stop sooner
2109/// than SkipUntil(tok::r_brace) would, but will never stop later.
2111 while (true) {
2112 switch (Tok.getKind()) {
2113 case tok::l_brace:
2114 // Skip until matching }, then stop. We've probably skipped over
2115 // a malformed class or function definition or similar.
2116 ConsumeBrace();
2117 SkipUntil(tok::r_brace);
2118 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
2119 // This declaration isn't over yet. Keep skipping.
2120 continue;
2121 }
2122 TryConsumeToken(tok::semi);
2123 return;
2124
2125 case tok::l_square:
2126 ConsumeBracket();
2127 SkipUntil(tok::r_square);
2128 continue;
2129
2130 case tok::l_paren:
2131 ConsumeParen();
2132 SkipUntil(tok::r_paren);
2133 continue;
2134
2135 case tok::r_brace:
2136 return;
2137
2138 case tok::semi:
2139 ConsumeToken();
2140 return;
2141
2142 case tok::kw_inline:
2143 // 'inline namespace' at the start of a line is almost certainly
2144 // a good place to pick back up parsing, except in an Objective-C
2145 // @interface context.
2146 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
2147 (!ParsingInObjCContainer || CurParsedObjCImpl))
2148 return;
2149 break;
2150
2151 case tok::kw_namespace:
2152 // 'namespace' at the start of a line is almost certainly a good
2153 // place to pick back up parsing, except in an Objective-C
2154 // @interface context.
2155 if (Tok.isAtStartOfLine() &&
2156 (!ParsingInObjCContainer || CurParsedObjCImpl))
2157 return;
2158 break;
2159
2160 case tok::at:
2161 // @end is very much like } in Objective-C contexts.
2162 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
2163 ParsingInObjCContainer)
2164 return;
2165 break;
2166
2167 case tok::minus:
2168 case tok::plus:
2169 // - and + probably start new method declarations in Objective-C contexts.
2170 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
2171 return;
2172 break;
2173
2174 case tok::eof:
2175 case tok::annot_module_begin:
2176 case tok::annot_module_end:
2177 case tok::annot_module_include:
2178 case tok::annot_repl_input_end:
2179 return;
2180
2181 default:
2182 break;
2183 }
2184
2186 }
2187}
2188
2189/// ParseDeclGroup - Having concluded that this is either a function
2190/// definition or a group of object declarations, actually parse the
2191/// result.
2192Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2193 DeclaratorContext Context,
2194 ParsedAttributes &Attrs,
2195 ParsedTemplateInfo &TemplateInfo,
2196 SourceLocation *DeclEnd,
2197 ForRangeInit *FRI) {
2198 // Parse the first declarator.
2199 // Consume all of the attributes from `Attrs` by moving them to our own local
2200 // list. This ensures that we will not attempt to interpret them as statement
2201 // attributes higher up the callchain.
2202 ParsedAttributes LocalAttrs(AttrFactory);
2203 LocalAttrs.takeAllFrom(Attrs);
2204 ParsingDeclarator D(*this, DS, LocalAttrs, Context);
2205 if (TemplateInfo.TemplateParams)
2206 D.setTemplateParameterLists(*TemplateInfo.TemplateParams);
2207
2208 bool IsTemplateSpecOrInst =
2209 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
2210 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
2211 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
2212
2213 ParseDeclarator(D);
2214
2215 if (IsTemplateSpecOrInst)
2216 SAC.done();
2217
2218 // Bail out if the first declarator didn't seem well-formed.
2219 if (!D.hasName() && !D.mayOmitIdentifier()) {
2221 return nullptr;
2222 }
2223
2224 if (getLangOpts().HLSL)
2225 MaybeParseHLSLSemantics(D);
2226
2227 if (Tok.is(tok::kw_requires))
2228 ParseTrailingRequiresClause(D);
2229
2230 // Save late-parsed attributes for now; they need to be parsed in the
2231 // appropriate function scope after the function Decl has been constructed.
2232 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2233 LateParsedAttrList LateParsedAttrs(true);
2234 if (D.isFunctionDeclarator()) {
2235 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2236
2237 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2238 // attribute. If we find the keyword here, tell the user to put it
2239 // at the start instead.
2240 if (Tok.is(tok::kw__Noreturn)) {
2242 const char *PrevSpec;
2243 unsigned DiagID;
2244
2245 // We can offer a fixit if it's valid to mark this function as _Noreturn
2246 // and we don't have any other declarators in this declaration.
2247 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2248 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2249 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2250
2251 Diag(Loc, diag::err_c11_noreturn_misplaced)
2252 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2253 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2254 : FixItHint());
2255 }
2256
2257 // Check to see if we have a function *definition* which must have a body.
2258 if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
2259 cutOffParsing();
2261 return nullptr;
2262 }
2263 // We're at the point where the parsing of function declarator is finished.
2264 //
2265 // A common error is that users accidently add a virtual specifier
2266 // (e.g. override) in an out-line method definition.
2267 // We attempt to recover by stripping all these specifiers coming after
2268 // the declarator.
2269 while (auto Specifier = isCXX11VirtSpecifier()) {
2270 Diag(Tok, diag::err_virt_specifier_outside_class)
2273 ConsumeToken();
2274 }
2275 // Look at the next token to make sure that this isn't a function
2276 // declaration. We have to check this because __attribute__ might be the
2277 // start of a function definition in GCC-extended K&R C.
2278 if (!isDeclarationAfterDeclarator()) {
2279
2280 // Function definitions are only allowed at file scope and in C++ classes.
2281 // The C++ inline method definition case is handled elsewhere, so we only
2282 // need to handle the file scope definition case.
2283 if (Context == DeclaratorContext::File) {
2284 if (isStartOfFunctionDefinition(D)) {
2285 // C++23 [dcl.typedef] p1:
2286 // The typedef specifier shall not be [...], and it shall not be
2287 // used in the decl-specifier-seq of a parameter-declaration nor in
2288 // the decl-specifier-seq of a function-definition.
2290 // If the user intended to write 'typename', we should have already
2291 // suggested adding it elsewhere. In any case, recover by ignoring
2292 // 'typedef' and suggest removing it.
2294 diag::err_function_declared_typedef)
2297 }
2298 Decl *TheDecl = nullptr;
2299
2300 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
2302 // If the declarator-id is not a template-id, issue a diagnostic
2303 // and recover by ignoring the 'template' keyword.
2304 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
2305 TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
2306 &LateParsedAttrs);
2307 } else {
2308 SourceLocation LAngleLoc =
2309 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2311 diag::err_explicit_instantiation_with_definition)
2312 << SourceRange(TemplateInfo.TemplateLoc)
2313 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2314
2315 // Recover as if it were an explicit specialization.
2316 TemplateParameterLists FakedParamLists;
2317 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2318 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc,
2319 std::nullopt, LAngleLoc, nullptr));
2320
2321 TheDecl = ParseFunctionDefinition(
2322 D,
2323 ParsedTemplateInfo(&FakedParamLists,
2324 /*isSpecialization=*/true,
2325 /*lastParameterListWasEmpty=*/true),
2326 &LateParsedAttrs);
2327 }
2328 } else {
2329 TheDecl =
2330 ParseFunctionDefinition(D, TemplateInfo, &LateParsedAttrs);
2331 }
2332
2333 return Actions.ConvertDeclToDeclGroup(TheDecl);
2334 }
2335
2336 if (isDeclarationSpecifier(ImplicitTypenameContext::No) ||
2337 Tok.is(tok::kw_namespace)) {
2338 // If there is an invalid declaration specifier or a namespace
2339 // definition right after the function prototype, then we must be in a
2340 // missing semicolon case where this isn't actually a body. Just fall
2341 // through into the code that handles it as a prototype, and let the
2342 // top-level code handle the erroneous declspec where it would
2343 // otherwise expect a comma or semicolon. Note that
2344 // isDeclarationSpecifier already covers 'inline namespace', since
2345 // 'inline' can be a declaration specifier.
2346 } else {
2347 Diag(Tok, diag::err_expected_fn_body);
2348 SkipUntil(tok::semi);
2349 return nullptr;
2350 }
2351 } else {
2352 if (Tok.is(tok::l_brace)) {
2353 Diag(Tok, diag::err_function_definition_not_allowed);
2355 return nullptr;
2356 }
2357 }
2358 }
2359 }
2360
2361 if (ParseAsmAttributesAfterDeclarator(D))
2362 return nullptr;
2363
2364 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2365 // must parse and analyze the for-range-initializer before the declaration is
2366 // analyzed.
2367 //
2368 // Handle the Objective-C for-in loop variable similarly, although we
2369 // don't need to parse the container in advance.
2370 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2371 bool IsForRangeLoop = false;
2372 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2373 IsForRangeLoop = true;
2374 EnterExpressionEvaluationContext ForRangeInitContext(
2376 /*LambdaContextDecl=*/nullptr,
2379
2380 // P2718R0 - Lifetime extension in range-based for loops.
2381 if (getLangOpts().CPlusPlus23) {
2382 auto &LastRecord = Actions.ExprEvalContexts.back();
2383 LastRecord.InLifetimeExtendingContext = true;
2384 }
2385
2386 if (getLangOpts().OpenMP)
2387 Actions.OpenMP().startOpenMPCXXRangeFor();
2388 if (Tok.is(tok::l_brace))
2389 FRI->RangeExpr = ParseBraceInitializer();
2390 else
2391 FRI->RangeExpr = ParseExpression();
2392
2393 // Before c++23, ForRangeLifetimeExtendTemps should be empty.
2394 assert(
2396 Actions.ExprEvalContexts.back().ForRangeLifetimeExtendTemps.empty());
2397
2398 // Move the collected materialized temporaries into ForRangeInit before
2399 // ForRangeInitContext exit.
2400 FRI->LifetimeExtendTemps = std::move(
2401 Actions.ExprEvalContexts.back().ForRangeLifetimeExtendTemps);
2402 }
2403
2404 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2405 if (IsForRangeLoop) {
2406 Actions.ActOnCXXForRangeDecl(ThisDecl);
2407 } else {
2408 // Obj-C for loop
2409 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2410 VD->setObjCForDecl(true);
2411 }
2412 Actions.FinalizeDeclaration(ThisDecl);
2413 D.complete(ThisDecl);
2414 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2415 }
2416
2417 SmallVector<Decl *, 8> DeclsInGroup;
2418 Decl *FirstDecl =
2419 ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo, FRI);
2420 if (LateParsedAttrs.size() > 0)
2421 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2422 D.complete(FirstDecl);
2423 if (FirstDecl)
2424 DeclsInGroup.push_back(FirstDecl);
2425
2426 bool ExpectSemi = Context != DeclaratorContext::ForInit;
2427
2428 // If we don't have a comma, it is either the end of the list (a ';') or an
2429 // error, bail out.
2430 SourceLocation CommaLoc;
2431 while (TryConsumeToken(tok::comma, CommaLoc)) {
2432 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2433 // This comma was followed by a line-break and something which can't be
2434 // the start of a declarator. The comma was probably a typo for a
2435 // semicolon.
2436 Diag(CommaLoc, diag::err_expected_semi_declaration)
2437 << FixItHint::CreateReplacement(CommaLoc, ";");
2438 ExpectSemi = false;
2439 break;
2440 }
2441
2442 // C++23 [temp.pre]p5:
2443 // In a template-declaration, explicit specialization, or explicit
2444 // instantiation the init-declarator-list in the declaration shall
2445 // contain at most one declarator.
2446 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
2447 D.isFirstDeclarator()) {
2448 Diag(CommaLoc, diag::err_multiple_template_declarators)
2449 << TemplateInfo.Kind;
2450 }
2451
2452 // Parse the next declarator.
2453 D.clear();
2454 D.setCommaLoc(CommaLoc);
2455
2456 // Accept attributes in an init-declarator. In the first declarator in a
2457 // declaration, these would be part of the declspec. In subsequent
2458 // declarators, they become part of the declarator itself, so that they
2459 // don't apply to declarators after *this* one. Examples:
2460 // short __attribute__((common)) var; -> declspec
2461 // short var __attribute__((common)); -> declarator
2462 // short x, __attribute__((common)) var; -> declarator
2463 MaybeParseGNUAttributes(D);
2464
2465 // MSVC parses but ignores qualifiers after the comma as an extension.
2466 if (getLangOpts().MicrosoftExt)
2467 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2468
2469 ParseDeclarator(D);
2470
2471 if (getLangOpts().HLSL)
2472 MaybeParseHLSLSemantics(D);
2473
2474 if (!D.isInvalidType()) {
2475 // C++2a [dcl.decl]p1
2476 // init-declarator:
2477 // declarator initializer[opt]
2478 // declarator requires-clause
2479 if (Tok.is(tok::kw_requires))
2480 ParseTrailingRequiresClause(D);
2481 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D, TemplateInfo);
2482 D.complete(ThisDecl);
2483 if (ThisDecl)
2484 DeclsInGroup.push_back(ThisDecl);
2485 }
2486 }
2487
2488 if (DeclEnd)
2489 *DeclEnd = Tok.getLocation();
2490
2491 if (ExpectSemi && ExpectAndConsumeSemi(
2492 Context == DeclaratorContext::File
2493 ? diag::err_invalid_token_after_toplevel_declarator
2494 : diag::err_expected_semi_declaration)) {
2495 // Okay, there was no semicolon and one was expected. If we see a
2496 // declaration specifier, just assume it was missing and continue parsing.
2497 // Otherwise things are very confused and we skip to recover.
2498 if (!isDeclarationSpecifier(ImplicitTypenameContext::No))
2500 }
2501
2502 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2503}
2504
2505/// Parse an optional simple-asm-expr and attributes, and attach them to a
2506/// declarator. Returns true on an error.
2507bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2508 // If a simple-asm-expr is present, parse it.
2509 if (Tok.is(tok::kw_asm)) {
2510 SourceLocation Loc;
2511 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2512 if (AsmLabel.isInvalid()) {
2513 SkipUntil(tok::semi, StopBeforeMatch);
2514 return true;
2515 }
2516
2517 D.setAsmLabel(AsmLabel.get());
2518 D.SetRangeEnd(Loc);
2519 }
2520
2521 MaybeParseGNUAttributes(D);
2522 return false;
2523}
2524
2525/// Parse 'declaration' after parsing 'declaration-specifiers
2526/// declarator'. This method parses the remainder of the declaration
2527/// (including any attributes or initializer, among other things) and
2528/// finalizes the declaration.
2529///
2530/// init-declarator: [C99 6.7]
2531/// declarator
2532/// declarator '=' initializer
2533/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2534/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2535/// [C++] declarator initializer[opt]
2536///
2537/// [C++] initializer:
2538/// [C++] '=' initializer-clause
2539/// [C++] '(' expression-list ')'
2540/// [C++0x] '=' 'default' [TODO]
2541/// [C++0x] '=' 'delete'
2542/// [C++0x] braced-init-list
2543///
2544/// According to the standard grammar, =default and =delete are function
2545/// definitions, but that definitely doesn't fit with the parser here.
2546///
2547Decl *Parser::ParseDeclarationAfterDeclarator(
2548 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2549 if (ParseAsmAttributesAfterDeclarator(D))
2550 return nullptr;
2551
2552 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2553}
2554
2555Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2556 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2557 // RAII type used to track whether we're inside an initializer.
2558 struct InitializerScopeRAII {
2559 Parser &P;
2560 Declarator &D;
2561 Decl *ThisDecl;
2562
2563 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2564 : P(P), D(D), ThisDecl(ThisDecl) {
2565 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2566 Scope *S = nullptr;
2567 if (D.getCXXScopeSpec().isSet()) {
2568 P.EnterScope(0);
2569 S = P.getCurScope();
2570 }
2571 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2572 }
2573 }
2574 ~InitializerScopeRAII() { pop(); }
2575 void pop() {
2576 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2577 Scope *S = nullptr;
2578 if (D.getCXXScopeSpec().isSet())
2579 S = P.getCurScope();
2580 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2581 if (S)
2582 P.ExitScope();
2583 }
2584 ThisDecl = nullptr;
2585 }
2586 };
2587
2588 enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
2589 InitKind TheInitKind;
2590 // If a '==' or '+=' is found, suggest a fixit to '='.
2591 if (isTokenEqualOrEqualTypo())
2592 TheInitKind = InitKind::Equal;
2593 else if (Tok.is(tok::l_paren))
2594 TheInitKind = InitKind::CXXDirect;
2595 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2596 (!CurParsedObjCImpl || !D.isFunctionDeclarator()))
2597 TheInitKind = InitKind::CXXBraced;
2598 else
2599 TheInitKind = InitKind::Uninitialized;
2600 if (TheInitKind != InitKind::Uninitialized)
2602
2603 // Inform Sema that we just parsed this declarator.
2604 Decl *ThisDecl = nullptr;
2605 Decl *OuterDecl = nullptr;
2606 switch (TemplateInfo.Kind) {
2607 case ParsedTemplateInfo::NonTemplate:
2608 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2609 break;
2610
2611 case ParsedTemplateInfo::Template:
2612 case ParsedTemplateInfo::ExplicitSpecialization: {
2613 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2614 *TemplateInfo.TemplateParams,
2615 D);
2616 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2617 // Re-direct this decl to refer to the templated decl so that we can
2618 // initialize it.
2619 ThisDecl = VT->getTemplatedDecl();
2620 OuterDecl = VT;
2621 }
2622 break;
2623 }
2624 case ParsedTemplateInfo::ExplicitInstantiation: {
2625 if (Tok.is(tok::semi)) {
2626 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2627 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2628 if (ThisRes.isInvalid()) {
2629 SkipUntil(tok::semi, StopBeforeMatch);
2630 return nullptr;
2631 }
2632 ThisDecl = ThisRes.get();
2633 } else {
2634 // FIXME: This check should be for a variable template instantiation only.
2635
2636 // Check that this is a valid instantiation
2638 // If the declarator-id is not a template-id, issue a diagnostic and
2639 // recover by ignoring the 'template' keyword.
2640 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2641 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2642 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2643 } else {
2644 SourceLocation LAngleLoc =
2645 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2647 diag::err_explicit_instantiation_with_definition)
2648 << SourceRange(TemplateInfo.TemplateLoc)
2649 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2650
2651 // Recover as if it were an explicit specialization.
2652 TemplateParameterLists FakedParamLists;
2653 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2654 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc,
2655 std::nullopt, LAngleLoc, nullptr));
2656
2657 ThisDecl =
2658 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2659 }
2660 }
2661 break;
2662 }
2663 }
2664
2667 switch (TheInitKind) {
2668 // Parse declarator '=' initializer.
2669 case InitKind::Equal: {
2670 SourceLocation EqualLoc = ConsumeToken();
2671
2672 if (Tok.is(tok::kw_delete)) {
2673 if (D.isFunctionDeclarator())
2674 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2675 << 1 /* delete */;
2676 else
2677 Diag(ConsumeToken(), diag::err_deleted_non_function);
2678 SkipDeletedFunctionBody();
2679 } else if (Tok.is(tok::kw_default)) {
2680 if (D.isFunctionDeclarator())
2681 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2682 << 0 /* default */;
2683 else
2684 Diag(ConsumeToken(), diag::err_default_special_members)
2685 << getLangOpts().CPlusPlus20;
2686 } else {
2687 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2688
2689 if (Tok.is(tok::code_completion)) {
2690 cutOffParsing();
2691 Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2692 Actions.FinalizeDeclaration(ThisDecl);
2693 return nullptr;
2694 }
2695
2696 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2697 ExprResult Init = ParseInitializer();
2698
2699 // If this is the only decl in (possibly) range based for statement,
2700 // our best guess is that the user meant ':' instead of '='.
2701 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2702 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2703 << FixItHint::CreateReplacement(EqualLoc, ":");
2704 // We are trying to stop parser from looking for ';' in this for
2705 // statement, therefore preventing spurious errors to be issued.
2706 FRI->ColonLoc = EqualLoc;
2707 Init = ExprError();
2708 FRI->RangeExpr = Init;
2709 }
2710
2711 InitScope.pop();
2712
2713 if (Init.isInvalid()) {
2715 StopTokens.push_back(tok::comma);
2718 StopTokens.push_back(tok::r_paren);
2719 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2720 Actions.ActOnInitializerError(ThisDecl);
2721 } else
2722 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2723 /*DirectInit=*/false);
2724 }
2725 break;
2726 }
2727 case InitKind::CXXDirect: {
2728 // Parse C++ direct initializer: '(' expression-list ')'
2729 BalancedDelimiterTracker T(*this, tok::l_paren);
2730 T.consumeOpen();
2731
2732 ExprVector Exprs;
2733
2734 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2735
2736 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2737 auto RunSignatureHelp = [&]() {
2738 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2739 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2740 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2741 /*Braced=*/false);
2742 CalledSignatureHelp = true;
2743 return PreferredType;
2744 };
2745 auto SetPreferredType = [&] {
2746 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2747 };
2748
2749 llvm::function_ref<void()> ExpressionStarts;
2750 if (ThisVarDecl) {
2751 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2752 // VarDecl. This is an error and it is reported in a call to
2753 // Actions.ActOnInitializerError(). However, we call
2754 // ProduceConstructorSignatureHelp only on VarDecls.
2755 ExpressionStarts = SetPreferredType;
2756 }
2757
2758 bool SawError = ParseExpressionList(Exprs, ExpressionStarts);
2759
2760 InitScope.pop();
2761
2762 if (SawError) {
2763 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2765 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2766 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2767 /*Braced=*/false);
2768 CalledSignatureHelp = true;
2769 }
2770 Actions.ActOnInitializerError(ThisDecl);
2771 SkipUntil(tok::r_paren, StopAtSemi);
2772 } else {
2773 // Match the ')'.
2774 T.consumeClose();
2775
2776 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2777 T.getCloseLocation(),
2778 Exprs);
2779 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2780 /*DirectInit=*/true);
2781 }
2782 break;
2783 }
2784 case InitKind::CXXBraced: {
2785 // Parse C++0x braced-init-list.
2786 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2787
2788 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2789
2790 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2791 ExprResult Init(ParseBraceInitializer());
2792
2793 InitScope.pop();
2794
2795 if (Init.isInvalid()) {
2796 Actions.ActOnInitializerError(ThisDecl);
2797 } else
2798 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2799 break;
2800 }
2801 case InitKind::Uninitialized: {
2802 Actions.ActOnUninitializedDecl(ThisDecl);
2803 break;
2804 }
2805 }
2806
2807 Actions.FinalizeDeclaration(ThisDecl);
2808 return OuterDecl ? OuterDecl : ThisDecl;
2809}
2810
2811/// ParseSpecifierQualifierList
2812/// specifier-qualifier-list:
2813/// type-specifier specifier-qualifier-list[opt]
2814/// type-qualifier specifier-qualifier-list[opt]
2815/// [GNU] attributes specifier-qualifier-list[opt]
2816///
2817void Parser::ParseSpecifierQualifierList(
2818 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2819 AccessSpecifier AS, DeclSpecContext DSC) {
2820 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2821 /// parse declaration-specifiers and complain about extra stuff.
2822 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2823 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC, nullptr,
2824 AllowImplicitTypename);
2825
2826 // Validate declspec for type-name.
2827 unsigned Specs = DS.getParsedSpecifiers();
2828 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2829 Diag(Tok, diag::err_expected_type);
2830 DS.SetTypeSpecError();
2831 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2832 Diag(Tok, diag::err_typename_requires_specqual);
2833 if (!DS.hasTypeSpecifier())
2834 DS.SetTypeSpecError();
2835 }
2836
2837 // Issue diagnostic and remove storage class if present.
2840 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2841 else
2843 diag::err_typename_invalid_storageclass);
2845 }
2846
2847 // Issue diagnostic and remove function specifier if present.
2848 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2849 if (DS.isInlineSpecified())
2850 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2851 if (DS.isVirtualSpecified())
2852 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2853 if (DS.hasExplicitSpecifier())
2854 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2855 if (DS.isNoreturnSpecified())
2856 Diag(DS.getNoreturnSpecLoc(), diag::err_typename_invalid_functionspec);
2857 DS.ClearFunctionSpecs();
2858 }
2859
2860 // Issue diagnostic and remove constexpr specifier if present.
2861 if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2862 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2863 << static_cast<int>(DS.getConstexprSpecifier());
2864 DS.ClearConstexprSpec();
2865 }
2866}
2867
2868/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2869/// specified token is valid after the identifier in a declarator which
2870/// immediately follows the declspec. For example, these things are valid:
2871///
2872/// int x [ 4]; // direct-declarator
2873/// int x ( int y); // direct-declarator
2874/// int(int x ) // direct-declarator
2875/// int x ; // simple-declaration
2876/// int x = 17; // init-declarator-list
2877/// int x , y; // init-declarator-list
2878/// int x __asm__ ("foo"); // init-declarator-list
2879/// int x : 4; // struct-declarator
2880/// int x { 5}; // C++'0x unified initializers
2881///
2882/// This is not, because 'x' does not immediately follow the declspec (though
2883/// ')' happens to be valid anyway).
2884/// int (x)
2885///
2887 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2888 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2889 tok::colon);
2890}
2891
2892/// ParseImplicitInt - This method is called when we have an non-typename
2893/// identifier in a declspec (which normally terminates the decl spec) when
2894/// the declspec has no type specifier. In this case, the declspec is either
2895/// malformed or is "implicit int" (in K&R and C89).
2896///
2897/// This method handles diagnosing this prettily and returns false if the
2898/// declspec is done being processed. If it recovers and thinks there may be
2899/// other pieces of declspec after it, it returns true.
2900///
2901bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2902 const ParsedTemplateInfo &TemplateInfo,
2903 AccessSpecifier AS, DeclSpecContext DSC,
2904 ParsedAttributes &Attrs) {
2905 assert(Tok.is(tok::identifier) && "should have identifier");
2906
2907 SourceLocation Loc = Tok.getLocation();
2908 // If we see an identifier that is not a type name, we normally would
2909 // parse it as the identifier being declared. However, when a typename
2910 // is typo'd or the definition is not included, this will incorrectly
2911 // parse the typename as the identifier name and fall over misparsing
2912 // later parts of the diagnostic.
2913 //
2914 // As such, we try to do some look-ahead in cases where this would
2915 // otherwise be an "implicit-int" case to see if this is invalid. For
2916 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2917 // an identifier with implicit int, we'd get a parse error because the
2918 // next token is obviously invalid for a type. Parse these as a case
2919 // with an invalid type specifier.
2920 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2921
2922 // Since we know that this either implicit int (which is rare) or an
2923 // error, do lookahead to try to do better recovery. This never applies
2924 // within a type specifier. Outside of C++, we allow this even if the
2925 // language doesn't "officially" support implicit int -- we support
2926 // implicit int as an extension in some language modes.
2927 if (!isTypeSpecifier(DSC) && getLangOpts().isImplicitIntAllowed() &&
2929 // If this token is valid for implicit int, e.g. "static x = 4", then
2930 // we just avoid eating the identifier, so it will be parsed as the
2931 // identifier in the declarator.
2932 return false;
2933 }
2934
2935 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2936 // for incomplete declarations such as `pipe p`.
2937 if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2938 return false;
2939
2940 if (getLangOpts().CPlusPlus &&
2942 // Don't require a type specifier if we have the 'auto' storage class
2943 // specifier in C++98 -- we'll promote it to a type specifier.
2944 if (SS)
2945 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2946 return false;
2947 }
2948
2949 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2950 getLangOpts().MSVCCompat) {
2951 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2952 // Give Sema a chance to recover if we are in a template with dependent base
2953 // classes.
2955 *Tok.getIdentifierInfo(), Tok.getLocation(),
2956 DSC == DeclSpecContext::DSC_template_type_arg)) {
2957 const char *PrevSpec;
2958 unsigned DiagID;
2959 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2960 Actions.getASTContext().getPrintingPolicy());
2961 DS.SetRangeEnd(Tok.getLocation());
2962 ConsumeToken();
2963 return false;
2964 }
2965 }
2966
2967 // Otherwise, if we don't consume this token, we are going to emit an
2968 // error anyway. Try to recover from various common problems. Check
2969 // to see if this was a reference to a tag name without a tag specified.
2970 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2971 //
2972 // C++ doesn't need this, and isTagName doesn't take SS.
2973 if (SS == nullptr) {
2974 const char *TagName = nullptr, *FixitTagName = nullptr;
2975 tok::TokenKind TagKind = tok::unknown;
2976
2977 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2978 default: break;
2979 case DeclSpec::TST_enum:
2980 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2982 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2984 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2986 TagName="__interface"; FixitTagName = "__interface ";
2987 TagKind=tok::kw___interface;break;
2989 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2990 }
2991
2992 if (TagName) {
2993 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2994 LookupResult R(Actions, TokenName, SourceLocation(),
2996
2997 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2998 << TokenName << TagName << getLangOpts().CPlusPlus
2999 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
3000
3001 if (Actions.LookupParsedName(R, getCurScope(), SS)) {
3002 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
3003 I != IEnd; ++I)
3004 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
3005 << TokenName << TagName;
3006 }
3007
3008 // Parse this as a tag as if the missing tag were present.
3009 if (TagKind == tok::kw_enum)
3010 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
3011 DeclSpecContext::DSC_normal);
3012 else
3013 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
3014 /*EnteringContext*/ false,
3015 DeclSpecContext::DSC_normal, Attrs);
3016 return true;
3017 }
3018 }
3019
3020 // Determine whether this identifier could plausibly be the name of something
3021 // being declared (with a missing type).
3022 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
3023 DSC == DeclSpecContext::DSC_class)) {
3024 // Look ahead to the next token to try to figure out what this declaration
3025 // was supposed to be.
3026 switch (NextToken().getKind()) {
3027 case tok::l_paren: {
3028 // static x(4); // 'x' is not a type
3029 // x(int n); // 'x' is not a type
3030 // x (*p)[]; // 'x' is a type
3031 //
3032 // Since we're in an error case, we can afford to perform a tentative
3033 // parse to determine which case we're in.
3034 TentativeParsingAction PA(*this);
3035 ConsumeToken();
3036 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
3037 PA.Revert();
3038
3039 if (TPR != TPResult::False) {
3040 // The identifier is followed by a parenthesized declarator.
3041 // It's supposed to be a type.
3042 break;
3043 }
3044
3045 // If we're in a context where we could be declaring a constructor,
3046 // check whether this is a constructor declaration with a bogus name.
3047 if (DSC == DeclSpecContext::DSC_class ||
3048 (DSC == DeclSpecContext::DSC_top_level && SS)) {
3050 if (Actions.isCurrentClassNameTypo(II, SS)) {
3051 Diag(Loc, diag::err_constructor_bad_name)
3052 << Tok.getIdentifierInfo() << II
3054 Tok.setIdentifierInfo(II);
3055 }
3056 }
3057 // Fall through.
3058 [[fallthrough]];
3059 }
3060 case tok::comma:
3061 case tok::equal:
3062 case tok::kw_asm:
3063 case tok::l_brace:
3064 case tok::l_square:
3065 case tok::semi:
3066 // This looks like a variable or function declaration. The type is
3067 // probably missing. We're done parsing decl-specifiers.
3068 // But only if we are not in a function prototype scope.
3069 if (getCurScope()->isFunctionPrototypeScope())
3070 break;
3071 if (SS)
3072 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
3073 return false;
3074
3075 default:
3076 // This is probably supposed to be a type. This includes cases like:
3077 // int f(itn);
3078 // struct S { unsigned : 4; };
3079 break;
3080 }
3081 }
3082
3083 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
3084 // and attempt to recover.
3085 ParsedType T;
3087 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
3088 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
3089 IsTemplateName);
3090 if (T) {
3091 // The action has suggested that the type T could be used. Set that as
3092 // the type in the declaration specifiers, consume the would-be type
3093 // name token, and we're done.
3094 const char *PrevSpec;
3095 unsigned DiagID;
3096 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
3097 Actions.getASTContext().getPrintingPolicy());
3098 DS.SetRangeEnd(Tok.getLocation());
3099 ConsumeToken();
3100 // There may be other declaration specifiers after this.
3101 return true;
3102 } else if (II != Tok.getIdentifierInfo()) {
3103 // If no type was suggested, the correction is to a keyword
3104 Tok.setKind(II->getTokenID());
3105 // There may be other declaration specifiers after this.
3106 return true;
3107 }
3108
3109 // Otherwise, the action had no suggestion for us. Mark this as an error.
3110 DS.SetTypeSpecError();
3111 DS.SetRangeEnd(Tok.getLocation());
3112 ConsumeToken();
3113
3114 // Eat any following template arguments.
3115 if (IsTemplateName) {
3116 SourceLocation LAngle, RAngle;
3117 TemplateArgList Args;
3118 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
3119 }
3120
3121 // TODO: Could inject an invalid typedef decl in an enclosing scope to
3122 // avoid rippling error messages on subsequent uses of the same type,
3123 // could be useful if #include was forgotten.
3124 return true;
3125}
3126
3127/// Determine the declaration specifier context from the declarator
3128/// context.
3129///
3130/// \param Context the declarator context, which is one of the
3131/// DeclaratorContext enumerator values.
3132Parser::DeclSpecContext
3133Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
3134 switch (Context) {
3136 return DeclSpecContext::DSC_class;
3138 return DeclSpecContext::DSC_top_level;
3140 return DeclSpecContext::DSC_template_param;
3142 return DeclSpecContext::DSC_template_arg;
3144 return DeclSpecContext::DSC_template_type_arg;
3147 return DeclSpecContext::DSC_trailing;
3150 return DeclSpecContext::DSC_alias_declaration;
3152 return DeclSpecContext::DSC_association;
3154 return DeclSpecContext::DSC_type_specifier;
3156 return DeclSpecContext::DSC_condition;
3158 return DeclSpecContext::DSC_conv_operator;
3160 return DeclSpecContext::DSC_new;
3175 return DeclSpecContext::DSC_normal;
3176 }
3177
3178 llvm_unreachable("Missing DeclaratorContext case");
3179}
3180
3181/// ParseAlignArgument - Parse the argument to an alignment-specifier.
3182///
3183/// [C11] type-id
3184/// [C11] constant-expression
3185/// [C++0x] type-id ...[opt]
3186/// [C++0x] assignment-expression ...[opt]
3187ExprResult Parser::ParseAlignArgument(StringRef KWName, SourceLocation Start,
3188 SourceLocation &EllipsisLoc, bool &IsType,
3190 ExprResult ER;
3191 if (isTypeIdInParens()) {
3193 ParsedType Ty = ParseTypeName().get();
3194 SourceRange TypeRange(Start, Tok.getLocation());
3195 if (Actions.ActOnAlignasTypeArgument(KWName, Ty, TypeLoc, TypeRange))
3196 return ExprError();
3197 TypeResult = Ty;
3198 IsType = true;
3199 } else {
3201 IsType = false;
3202 }
3203
3205 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3206
3207 return ER;
3208}
3209
3210/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
3211/// attribute to Attrs.
3212///
3213/// alignment-specifier:
3214/// [C11] '_Alignas' '(' type-id ')'
3215/// [C11] '_Alignas' '(' constant-expression ')'
3216/// [C++11] 'alignas' '(' type-id ...[opt] ')'
3217/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
3218void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
3219 SourceLocation *EndLoc) {
3220 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
3221 "Not an alignment-specifier!");
3222 Token KWTok = Tok;
3223 IdentifierInfo *KWName = KWTok.getIdentifierInfo();
3224 auto Kind = KWTok.getKind();
3225 SourceLocation KWLoc = ConsumeToken();
3226
3227 BalancedDelimiterTracker T(*this, tok::l_paren);
3228 if (T.expectAndConsume())
3229 return;
3230
3231 bool IsType;
3233 SourceLocation EllipsisLoc;
3234 ExprResult ArgExpr =
3235 ParseAlignArgument(PP.getSpelling(KWTok), T.getOpenLocation(),
3236 EllipsisLoc, IsType, TypeResult);
3237 if (ArgExpr.isInvalid()) {
3238 T.skipToEnd();
3239 return;
3240 }
3241
3242 T.consumeClose();
3243 if (EndLoc)
3244 *EndLoc = T.getCloseLocation();
3245
3246 if (IsType) {
3247 Attrs.addNewTypeAttr(KWName, KWLoc, nullptr, KWLoc, TypeResult, Kind,
3248 EllipsisLoc);
3249 } else {
3250 ArgsVector ArgExprs;
3251 ArgExprs.push_back(ArgExpr.get());
3252 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1, Kind,
3253 EllipsisLoc);
3254 }
3255}
3256
3257/// Bounds attributes (e.g., counted_by):
3258/// AttrName '(' expression ')'
3259void Parser::ParseBoundsAttribute(IdentifierInfo &AttrName,
3260 SourceLocation AttrNameLoc,
3261 ParsedAttributes &Attrs,
3262 IdentifierInfo *ScopeName,
3263 SourceLocation ScopeLoc,
3264 ParsedAttr::Form Form) {
3265 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
3266
3267 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3268 Parens.consumeOpen();
3269
3270 if (Tok.is(tok::r_paren)) {
3271 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
3272 Parens.consumeClose();
3273 return;
3274 }
3275
3276 ArgsVector ArgExprs;
3277 // Don't evaluate argument when the attribute is ignored.
3278 using ExpressionKind =
3282 ExpressionKind::EK_BoundsAttrArgument);
3283
3284 ExprResult ArgExpr(
3286
3287 if (ArgExpr.isInvalid()) {
3288 Parens.skipToEnd();
3289 return;
3290 }
3291
3292 ArgExprs.push_back(ArgExpr.get());
3293 Parens.consumeClose();
3294
3295 ASTContext &Ctx = Actions.getASTContext();
3296
3297 ArgExprs.push_back(IntegerLiteral::Create(
3298 Ctx, llvm::APInt(Ctx.getTypeSize(Ctx.getSizeType()), 0),
3299 Ctx.getSizeType(), SourceLocation()));
3300
3301 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
3302 ScopeName, ScopeLoc, ArgExprs.data(), ArgExprs.size(), Form);
3303}
3304
3305ExprResult Parser::ParseExtIntegerArgument() {
3306 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
3307 "Not an extended int type");
3308 ConsumeToken();
3309
3310 BalancedDelimiterTracker T(*this, tok::l_paren);
3311 if (T.expectAndConsume())
3312 return ExprError();
3313
3315 if (ER.isInvalid()) {
3316 T.skipToEnd();
3317 return ExprError();
3318 }
3319
3320 if(T.consumeClose())
3321 return ExprError();
3322 return ER;
3323}
3324
3325/// Determine whether we're looking at something that might be a declarator
3326/// in a simple-declaration. If it can't possibly be a declarator, maybe
3327/// diagnose a missing semicolon after a prior tag definition in the decl
3328/// specifier.
3329///
3330/// \return \c true if an error occurred and this can't be any kind of
3331/// declaration.
3332bool
3333Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
3334 DeclSpecContext DSContext,
3335 LateParsedAttrList *LateAttrs) {
3336 assert(DS.hasTagDefinition() && "shouldn't call this");
3337
3338 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3339 DSContext == DeclSpecContext::DSC_top_level);
3340
3341 if (getLangOpts().CPlusPlus &&
3342 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
3343 tok::annot_template_id) &&
3344 TryAnnotateCXXScopeToken(EnteringContext)) {
3346 return true;
3347 }
3348
3349 bool HasScope = Tok.is(tok::annot_cxxscope);
3350 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
3351 Token AfterScope = HasScope ? NextToken() : Tok;
3352
3353 // Determine whether the following tokens could possibly be a
3354 // declarator.
3355 bool MightBeDeclarator = true;
3356 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
3357 // A declarator-id can't start with 'typename'.
3358 MightBeDeclarator = false;
3359 } else if (AfterScope.is(tok::annot_template_id)) {
3360 // If we have a type expressed as a template-id, this cannot be a
3361 // declarator-id (such a type cannot be redeclared in a simple-declaration).
3362 TemplateIdAnnotation *Annot =
3363 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
3364 if (Annot->Kind == TNK_Type_template)
3365 MightBeDeclarator = false;
3366 } else if (AfterScope.is(tok::identifier)) {
3367 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
3368
3369 // These tokens cannot come after the declarator-id in a
3370 // simple-declaration, and are likely to come after a type-specifier.
3371 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
3372 tok::annot_cxxscope, tok::coloncolon)) {
3373 // Missing a semicolon.
3374 MightBeDeclarator = false;
3375 } else if (HasScope) {
3376 // If the declarator-id has a scope specifier, it must redeclare a
3377 // previously-declared entity. If that's a type (and this is not a
3378 // typedef), that's an error.
3379 CXXScopeSpec SS;
3381 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3382 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
3383 Sema::NameClassification Classification = Actions.ClassifyName(
3384 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
3385 /*CCC=*/nullptr);
3386 switch (Classification.getKind()) {
3387 case Sema::NC_Error:
3389 return true;
3390
3391 case Sema::NC_Keyword:
3392 llvm_unreachable("typo correction is not possible here");
3393
3394 case Sema::NC_Type:
3398 // Not a previously-declared non-type entity.
3399 MightBeDeclarator = false;
3400 break;
3401
3402 case Sema::NC_Unknown:
3403 case Sema::NC_NonType:
3408 case Sema::NC_Concept:
3409 // Might be a redeclaration of a prior entity.
3410 break;
3411 }
3412 }
3413 }
3414
3415 if (MightBeDeclarator)
3416 return false;
3417
3418 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
3420 diag::err_expected_after)
3421 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
3422
3423 // Try to recover from the typo, by dropping the tag definition and parsing
3424 // the problematic tokens as a type.
3425 //
3426 // FIXME: Split the DeclSpec into pieces for the standalone
3427 // declaration and pieces for the following declaration, instead
3428 // of assuming that all the other pieces attach to new declaration,
3429 // and call ParsedFreeStandingDeclSpec as appropriate.
3430 DS.ClearTypeSpecType();
3431 ParsedTemplateInfo NotATemplate;
3432 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
3433 return false;
3434}
3435
3436/// ParseDeclarationSpecifiers
3437/// declaration-specifiers: [C99 6.7]
3438/// storage-class-specifier declaration-specifiers[opt]
3439/// type-specifier declaration-specifiers[opt]
3440/// [C99] function-specifier declaration-specifiers[opt]
3441/// [C11] alignment-specifier declaration-specifiers[opt]
3442/// [GNU] attributes declaration-specifiers[opt]
3443/// [Clang] '__module_private__' declaration-specifiers[opt]
3444/// [ObjC1] '__kindof' declaration-specifiers[opt]
3445///
3446/// storage-class-specifier: [C99 6.7.1]
3447/// 'typedef'
3448/// 'extern'
3449/// 'static'
3450/// 'auto'
3451/// 'register'
3452/// [C++] 'mutable'
3453/// [C++11] 'thread_local'
3454/// [C11] '_Thread_local'
3455/// [GNU] '__thread'
3456/// function-specifier: [C99 6.7.4]
3457/// [C99] 'inline'
3458/// [C++] 'virtual'
3459/// [C++] 'explicit'
3460/// [OpenCL] '__kernel'
3461/// 'friend': [C++ dcl.friend]
3462/// 'constexpr': [C++0x dcl.constexpr]
3463void Parser::ParseDeclarationSpecifiers(
3464 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
3465 DeclSpecContext DSContext, LateParsedAttrList *LateAttrs,
3466 ImplicitTypenameContext AllowImplicitTypename) {
3467 if (DS.getSourceRange().isInvalid()) {
3468 // Start the range at the current token but make the end of the range
3469 // invalid. This will make the entire range invalid unless we successfully
3470 // consume a token.
3471 DS.SetRangeStart(Tok.getLocation());
3473 }
3474
3475 // If we are in a operator context, convert it back into a type specifier
3476 // context for better error handling later on.
3477 if (DSContext == DeclSpecContext::DSC_conv_operator) {
3478 // No implicit typename here.
3479 AllowImplicitTypename = ImplicitTypenameContext::No;
3480 DSContext = DeclSpecContext::DSC_type_specifier;
3481 }
3482
3483 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3484 DSContext == DeclSpecContext::DSC_top_level);
3485 bool AttrsLastTime = false;
3486 ParsedAttributes attrs(AttrFactory);
3487 // We use Sema's policy to get bool macros right.
3488 PrintingPolicy Policy = Actions.getPrintingPolicy();
3489 while (true) {
3490 bool isInvalid = false;
3491 bool isStorageClass = false;
3492 const char *PrevSpec = nullptr;
3493 unsigned DiagID = 0;
3494
3495 // This value needs to be set to the location of the last token if the last
3496 // token of the specifier is already consumed.
3497 SourceLocation ConsumedEnd;
3498
3499 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3500 // implementation for VS2013 uses _Atomic as an identifier for one of the
3501 // classes in <atomic>.
3502 //
3503 // A typedef declaration containing _Atomic<...> is among the places where
3504 // the class is used. If we are currently parsing such a declaration, treat
3505 // the token as an identifier.
3506 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3508 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3509 Tok.setKind(tok::identifier);
3510
3511 SourceLocation Loc = Tok.getLocation();
3512
3513 // Helper for image types in OpenCL.
3514 auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
3515 // Check if the image type is supported and otherwise turn the keyword into an identifier
3516 // because image types from extensions are not reserved identifiers.
3517 if (!StringRef(Ext).empty() && !getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())) {
3519 Tok.setKind(tok::identifier);
3520 return false;
3521 }
3522 isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3523 return true;
3524 };
3525
3526 // Turn off usual access checking for template specializations and
3527 // instantiations.
3528 bool IsTemplateSpecOrInst =
3529 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3530 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3531
3532 switch (Tok.getKind()) {
3533 default:
3534 if (Tok.isRegularKeywordAttribute())
3535 goto Attribute;
3536
3537 DoneWithDeclSpec:
3538 if (!AttrsLastTime)
3539 ProhibitAttributes(attrs);
3540 else {
3541 // Reject C++11 / C23 attributes that aren't type attributes.
3542 for (const ParsedAttr &PA : attrs) {
3543 if (!PA.isCXX11Attribute() && !PA.isC23Attribute() &&
3544 !PA.isRegularKeywordAttribute())
3545 continue;
3546 if (PA.getKind() == ParsedAttr::UnknownAttribute)
3547 // We will warn about the unknown attribute elsewhere (in
3548 // SemaDeclAttr.cpp)
3549 continue;
3550 // GCC ignores this attribute when placed on the DeclSpec in [[]]
3551 // syntax, so we do the same.
3552 if (PA.getKind() == ParsedAttr::AT_VectorSize) {
3553 Diag(PA.getLoc(), diag::warn_attribute_ignored) << PA;
3554 PA.setInvalid();
3555 continue;
3556 }
3557 // We reject AT_LifetimeBound and AT_AnyX86NoCfCheck, even though they
3558 // are type attributes, because we historically haven't allowed these
3559 // to be used as type attributes in C++11 / C23 syntax.
3560 if (PA.isTypeAttr() && PA.getKind() != ParsedAttr::AT_LifetimeBound &&
3561 PA.getKind() != ParsedAttr::AT_AnyX86NoCfCheck)
3562 continue;
3563 Diag(PA.getLoc(), diag::err_attribute_not_type_attr)
3564 << PA << PA.isRegularKeywordAttribute();
3565 PA.setInvalid();
3566 }
3567
3568 DS.takeAttributesFrom(attrs);
3569 }
3570
3571 // If this is not a declaration specifier token, we're done reading decl
3572 // specifiers. First verify that DeclSpec's are consistent.
3573 DS.Finish(Actions, Policy);
3574 return;
3575
3576 // alignment-specifier
3577 case tok::kw__Alignas:
3578 diagnoseUseOfC11Keyword(Tok);
3579 [[fallthrough]];
3580 case tok::kw_alignas:
3581 // _Alignas and alignas (C23, not C++) should parse the same way. The C++
3582 // parsing for alignas happens through the usual attribute parsing. This
3583 // ensures that an alignas specifier can appear in a type position in C
3584 // despite that not being valid in C++.
3585 if (getLangOpts().C23 || Tok.getKind() == tok::kw__Alignas) {
3586 if (Tok.getKind() == tok::kw_alignas)
3587 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
3588 ParseAlignmentSpecifier(DS.getAttributes());
3589 continue;
3590 }
3591 [[fallthrough]];
3592 case tok::l_square:
3593 if (!isAllowedCXX11AttributeSpecifier())
3594 goto DoneWithDeclSpec;
3595
3596 Attribute:
3597 ProhibitAttributes(attrs);
3598 // FIXME: It would be good to recover by accepting the attributes,
3599 // but attempting to do that now would cause serious
3600 // madness in terms of diagnostics.
3601 attrs.clear();
3602 attrs.Range = SourceRange();
3603
3604 ParseCXX11Attributes(attrs);
3605 AttrsLastTime = true;
3606 continue;
3607
3608 case tok::code_completion: {
3610 if (DS.hasTypeSpecifier()) {
3611 bool AllowNonIdentifiers
3616 Scope::AtCatchScope)) == 0;
3617 bool AllowNestedNameSpecifiers
3618 = DSContext == DeclSpecContext::DSC_top_level ||
3619 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3620
3621 cutOffParsing();
3622 Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3623 AllowNonIdentifiers,
3624 AllowNestedNameSpecifiers);
3625 return;
3626 }
3627
3628 // Class context can appear inside a function/block, so prioritise that.
3629 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3630 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3632 else if (DSContext == DeclSpecContext::DSC_class)
3633 CCC = Sema::PCC_Class;
3634 else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3636 else if (CurParsedObjCImpl)
3638
3639 cutOffParsing();
3640 Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3641 return;
3642 }
3643
3644 case tok::coloncolon: // ::foo::bar
3645 // C++ scope specifier. Annotate and loop, or bail out on error.
3646 if (getLangOpts().CPlusPlus &&
3647 TryAnnotateCXXScopeToken(EnteringContext)) {
3648 if (!DS.hasTypeSpecifier())
3649 DS.SetTypeSpecError();
3650 goto DoneWithDeclSpec;
3651 }
3652 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3653 goto DoneWithDeclSpec;
3654 continue;
3655
3656 case tok::annot_cxxscope: {
3657 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3658 goto DoneWithDeclSpec;
3659
3660 CXXScopeSpec SS;
3661 if (TemplateInfo.TemplateParams)
3662 SS.setTemplateParamLists(*TemplateInfo.TemplateParams);
3664 Tok.getAnnotationRange(),
3665 SS);
3666
3667 // We are looking for a qualified typename.
3668 Token Next = NextToken();
3669
3670 TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3671 ? takeTemplateIdAnnotation(Next)
3672 : nullptr;
3673 if (TemplateId && TemplateId->hasInvalidName()) {
3674 // We found something like 'T::U<Args> x', but U is not a template.
3675 // Assume it was supposed to be a type.
3676 DS.SetTypeSpecError();
3677 ConsumeAnnotationToken();
3678 break;
3679 }
3680
3681 if (TemplateId && TemplateId->Kind == TNK_Type_template) {
3682 // We have a qualified template-id, e.g., N::A<int>
3683
3684 // If this would be a valid constructor declaration with template
3685 // arguments, we will reject the attempt to form an invalid type-id
3686 // referring to the injected-class-name when we annotate the token,
3687 // per C++ [class.qual]p2.
3688 //
3689 // To improve diagnostics for this case, parse the declaration as a
3690 // constructor (and reject the extra template arguments later).
3691 if ((DSContext == DeclSpecContext::DSC_top_level ||
3692 DSContext == DeclSpecContext::DSC_class) &&
3693 TemplateId->Name &&
3694 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3695 isConstructorDeclarator(/*Unqualified=*/false,
3696 /*DeductionGuide=*/false,
3697 DS.isFriendSpecified())) {
3698 // The user meant this to be an out-of-line constructor
3699 // definition, but template arguments are not allowed
3700 // there. Just allow this as a constructor; we'll
3701 // complain about it later.
3702 goto DoneWithDeclSpec;
3703 }
3704
3705 DS.getTypeSpecScope() = SS;
3706 ConsumeAnnotationToken(); // The C++ scope.
3707 assert(Tok.is(tok::annot_template_id) &&
3708 "ParseOptionalCXXScopeSpecifier not working");
3709 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3710 continue;
3711 }
3712
3713 if (TemplateId && TemplateId->Kind == TNK_Concept_template) {
3714 DS.getTypeSpecScope() = SS;
3715 // This is probably a qualified placeholder-specifier, e.g., ::C<int>
3716 // auto ... Consume the scope annotation and continue to consume the
3717 // template-id as a placeholder-specifier. Let the next iteration
3718 // diagnose a missing auto.
3719 ConsumeAnnotationToken();
3720 continue;
3721 }
3722
3723 if (Next.is(tok::annot_typename)) {
3724 DS.getTypeSpecScope() = SS;
3725 ConsumeAnnotationToken(); // The C++ scope.
3728 Tok.getAnnotationEndLoc(),
3729 PrevSpec, DiagID, T, Policy);
3730 if (isInvalid)
3731 break;
3733 ConsumeAnnotationToken(); // The typename
3734 }
3735
3736 if (AllowImplicitTypename == ImplicitTypenameContext::Yes &&
3737 Next.is(tok::annot_template_id) &&
3738 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3740 DS.getTypeSpecScope() = SS;
3741 ConsumeAnnotationToken(); // The C++ scope.
3742 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3743 continue;
3744 }
3745
3746 if (Next.isNot(tok::identifier))
3747 goto DoneWithDeclSpec;
3748
3749 // Check whether this is a constructor declaration. If we're in a
3750 // context where the identifier could be a class name, and it has the
3751 // shape of a constructor declaration, process it as one.
3752 if ((DSContext == DeclSpecContext::DSC_top_level ||
3753 DSContext == DeclSpecContext::DSC_class) &&
3754 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3755 &SS) &&
3756 isConstructorDeclarator(/*Unqualified=*/false,
3757 /*DeductionGuide=*/false,
3758 DS.isFriendSpecified(),
3759 &TemplateInfo))
3760 goto DoneWithDeclSpec;
3761
3762 // C++20 [temp.spec] 13.9/6.
3763 // This disables the access checking rules for function template explicit
3764 // instantiation and explicit specialization:
3765 // - `return type`.
3766 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3767
3768 ParsedType TypeRep = Actions.getTypeName(
3769 *Next.getIdentifierInfo(), Next.getLocation(), getCurScope(), &SS,
3770 false, false, nullptr,
3771 /*IsCtorOrDtorName=*/false,
3772 /*WantNontrivialTypeSourceInfo=*/true,
3773 isClassTemplateDeductionContext(DSContext), AllowImplicitTypename);
3774
3775 if (IsTemplateSpecOrInst)
3776 SAC.done();
3777
3778 // If the referenced identifier is not a type, then this declspec is
3779 // erroneous: We already checked about that it has no type specifier, and
3780 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3781 // typename.
3782 if (!TypeRep) {
3783 if (TryAnnotateTypeConstraint())
3784 goto DoneWithDeclSpec;
3785 if (Tok.isNot(tok::annot_cxxscope) ||
3786 NextToken().isNot(tok::identifier))
3787 continue;
3788 // Eat the scope spec so the identifier is current.
3789 ConsumeAnnotationToken();
3790 ParsedAttributes Attrs(AttrFactory);
3791 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3792 if (!Attrs.empty()) {
3793 AttrsLastTime = true;
3794 attrs.takeAllFrom(Attrs);
3795 }
3796 continue;
3797 }
3798 goto DoneWithDeclSpec;
3799 }
3800
3801 DS.getTypeSpecScope() = SS;
3802 ConsumeAnnotationToken(); // The C++ scope.
3803
3805 DiagID, TypeRep, Policy);
3806 if (isInvalid)
3807 break;
3808
3809 DS.SetRangeEnd(Tok.getLocation());
3810 ConsumeToken(); // The typename.
3811
3812 continue;
3813 }
3814
3815 case tok::annot_typename: {
3816 // If we've previously seen a tag definition, we were almost surely
3817 // missing a semicolon after it.
3818 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3819 goto DoneWithDeclSpec;
3820
3823 DiagID, T, Policy);
3824 if (isInvalid)
3825 break;
3826
3828 ConsumeAnnotationToken(); // The typename
3829
3830 continue;
3831 }
3832
3833 case tok::kw___is_signed:
3834 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3835 // typically treats it as a trait. If we see __is_signed as it appears
3836 // in libstdc++, e.g.,
3837 //
3838 // static const bool __is_signed;
3839 //
3840 // then treat __is_signed as an identifier rather than as a keyword.
3841 if (DS.getTypeSpecType() == TST_bool &&
3844 TryKeywordIdentFallback(true);
3845
3846 // We're done with the declaration-specifiers.
3847 goto DoneWithDeclSpec;
3848
3849 // typedef-name
3850 case tok::kw___super:
3851 case tok::kw_decltype:
3852 case tok::identifier:
3853 ParseIdentifier: {
3854 // This identifier can only be a typedef name if we haven't already seen
3855 // a type-specifier. Without this check we misparse:
3856 // typedef int X; struct Y { short X; }; as 'short int'.
3857 if (DS.hasTypeSpecifier())
3858 goto DoneWithDeclSpec;
3859
3860 // If the token is an identifier named "__declspec" and Microsoft
3861 // extensions are not enabled, it is likely that there will be cascading
3862 // parse errors if this really is a __declspec attribute. Attempt to
3863 // recognize that scenario and recover gracefully.
3864 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3865 Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3866 Diag(Loc, diag::err_ms_attributes_not_enabled);
3867
3868 // The next token should be an open paren. If it is, eat the entire
3869 // attribute declaration and continue.
3870 if (NextToken().is(tok::l_paren)) {
3871 // Consume the __declspec identifier.
3872 ConsumeToken();
3873
3874 // Eat the parens and everything between them.
3875 BalancedDelimiterTracker T(*this, tok::l_paren);
3876 if (T.consumeOpen()) {
3877 assert(false && "Not a left paren?");
3878 return;
3879 }
3880 T.skipToEnd();
3881 continue;
3882 }
3883 }
3884
3885 // In C++, check to see if this is a scope specifier like foo::bar::, if
3886 // so handle it as such. This is important for ctor parsing.
3887 if (getLangOpts().CPlusPlus) {
3888 // C++20 [temp.spec] 13.9/6.
3889 // This disables the access checking rules for function template
3890 // explicit instantiation and explicit specialization:
3891 // - `return type`.
3892 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3893
3894 const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
3895
3896 if (IsTemplateSpecOrInst)
3897 SAC.done();
3898
3899 if (Success) {
3900 if (IsTemplateSpecOrInst)
3901 SAC.redelay();
3902 DS.SetTypeSpecError();
3903 goto DoneWithDeclSpec;
3904 }
3905
3906 if (!Tok.is(tok::identifier))
3907 continue;
3908 }
3909
3910 // Check for need to substitute AltiVec keyword tokens.
3911 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3912 break;
3913
3914 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3915 // allow the use of a typedef name as a type specifier.
3916 if (DS.isTypeAltiVecVector())
3917 goto DoneWithDeclSpec;
3918
3919 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3920 isObjCInstancetype()) {
3921 ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3922 assert(TypeRep);
3924 DiagID, TypeRep, Policy);
3925 if (isInvalid)
3926 break;
3927
3928 DS.SetRangeEnd(Loc);
3929 ConsumeToken();
3930 continue;
3931 }
3932
3933 // If we're in a context where the identifier could be a class name,
3934 // check whether this is a constructor declaration.
3935 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3937 isConstructorDeclarator(/*Unqualified=*/true,
3938 /*DeductionGuide=*/false,
3939 DS.isFriendSpecified()))
3940 goto DoneWithDeclSpec;
3941
3942 ParsedType TypeRep = Actions.getTypeName(
3943 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3944 false, false, nullptr, false, false,
3945 isClassTemplateDeductionContext(DSContext));
3946
3947 // If this is not a typedef name, don't parse it as part of the declspec,
3948 // it must be an implicit int or an error.
3949 if (!TypeRep) {
3950 if (TryAnnotateTypeConstraint())
3951 goto DoneWithDeclSpec;
3952 if (Tok.isNot(tok::identifier))
3953 continue;
3954 ParsedAttributes Attrs(AttrFactory);
3955 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3956 if (!Attrs.empty()) {
3957 AttrsLastTime = true;
3958 attrs.takeAllFrom(Attrs);
3959 }
3960 continue;
3961 }
3962 goto DoneWithDeclSpec;
3963 }
3964
3965 // Likewise, if this is a context where the identifier could be a template
3966 // name, check whether this is a deduction guide declaration.
3967 CXXScopeSpec SS;
3968 if (getLangOpts().CPlusPlus17 &&
3969 (DSContext == DeclSpecContext::DSC_class ||
3970 DSContext == DeclSpecContext::DSC_top_level) &&
3972 Tok.getLocation(), SS) &&
3973 isConstructorDeclarator(/*Unqualified*/ true,
3974 /*DeductionGuide*/ true))
3975 goto DoneWithDeclSpec;
3976
3978 DiagID, TypeRep, Policy);
3979 if (isInvalid)
3980 break;
3981
3982 DS.SetRangeEnd(Tok.getLocation());
3983 ConsumeToken(); // The identifier
3984
3985 // Objective-C supports type arguments and protocol references
3986 // following an Objective-C object or object pointer
3987 // type. Handle either one of them.
3988 if (Tok.is(tok::less) && getLangOpts().ObjC) {
3989 SourceLocation NewEndLoc;
3990 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3991 Loc, TypeRep, /*consumeLastToken=*/true,
3992 NewEndLoc);
3993 if (NewTypeRep.isUsable()) {
3994 DS.UpdateTypeRep(NewTypeRep.get());
3995 DS.SetRangeEnd(NewEndLoc);
3996 }
3997 }
3998
3999 // Need to support trailing type qualifiers (e.g. "id<p> const").
4000 // If a type specifier follows, it will be diagnosed elsewhere.
4001 continue;
4002 }
4003
4004 // type-name or placeholder-specifier
4005 case tok::annot_template_id: {
4006 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
4007
4008 if (TemplateId->hasInvalidName()) {
4009 DS.SetTypeSpecError();
4010 break;
4011 }
4012
4013 if (TemplateId->Kind == TNK_Concept_template) {
4014 // If we've already diagnosed that this type-constraint has invalid
4015 // arguments, drop it and just form 'auto' or 'decltype(auto)'.
4016 if (TemplateId->hasInvalidArgs())
4017 TemplateId = nullptr;
4018
4019 // Any of the following tokens are likely the start of the user
4020 // forgetting 'auto' or 'decltype(auto)', so diagnose.
4021 // Note: if updating this list, please make sure we update
4022 // isCXXDeclarationSpecifier's check for IsPlaceholderSpecifier to have
4023 // a matching list.
4024 if (NextToken().isOneOf(tok::identifier, tok::kw_const,
4025 tok::kw_volatile, tok::kw_restrict, tok::amp,
4026 tok::ampamp)) {
4027 Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
4028 << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
4029 // Attempt to continue as if 'auto' was placed here.
4030 isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
4031 TemplateId, Policy);
4032 break;
4033 }
4034 if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
4035 goto DoneWithDeclSpec;
4036
4037 if (TemplateId && !isInvalid && Actions.CheckTypeConstraint(TemplateId))
4038 TemplateId = nullptr;
4039
4040 ConsumeAnnotationToken();
4041 SourceLocation AutoLoc = Tok.getLocation();
4042 if (TryConsumeToken(tok::kw_decltype)) {
4043 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4044 if (Tracker.consumeOpen()) {
4045 // Something like `void foo(Iterator decltype i)`
4046 Diag(Tok, diag::err_expected) << tok::l_paren;
4047 } else {
4048 if (!TryConsumeToken(tok::kw_auto)) {
4049 // Something like `void foo(Iterator decltype(int) i)`
4050 Tracker.skipToEnd();
4051 Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
4053 Tok.getLocation()),
4054 "auto");
4055 } else {
4056 Tracker.consumeClose();
4057 }
4058 }
4059 ConsumedEnd = Tok.getLocation();
4060 DS.setTypeArgumentRange(Tracker.getRange());
4061 // Even if something went wrong above, continue as if we've seen
4062 // `decltype(auto)`.
4063 isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
4064 DiagID, TemplateId, Policy);
4065 } else {
4066 isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
4067 TemplateId, Policy);
4068 }
4069 break;
4070 }
4071
4072 if (TemplateId->Kind != TNK_Type_template &&
4073 TemplateId->Kind != TNK_Undeclared_template) {
4074 // This template-id does not refer to a type name, so we're
4075 // done with the type-specifiers.
4076 goto DoneWithDeclSpec;
4077 }
4078
4079 // If we're in a context where the template-id could be a
4080 // constructor name or specialization, check whether this is a
4081 // constructor declaration.
4082 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
4083 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
4084 isConstructorDeclarator(/*Unqualified=*/true,
4085 /*DeductionGuide=*/false,
4086 DS.isFriendSpecified()))
4087 goto DoneWithDeclSpec;
4088
4089 // Turn the template-id annotation token into a type annotation
4090 // token, then try again to parse it as a type-specifier.
4091 CXXScopeSpec SS;
4092 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
4093 continue;
4094 }
4095
4096 // Attributes support.
4097 case tok::kw___attribute:
4098 case tok::kw___declspec:
4099 ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), LateAttrs);
4100 continue;
4101
4102 // Microsoft single token adornments.
4103 case tok::kw___forceinline: {
4104 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
4105 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
4106 SourceLocation AttrNameLoc = Tok.getLocation();
4107 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
4108 nullptr, 0, tok::kw___forceinline);
4109 break;
4110 }
4111
4112 case tok::kw___unaligned:
4113 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
4114 getLangOpts());
4115 break;
4116
4117 case tok::kw___sptr:
4118 case tok::kw___uptr:
4119 case tok::kw___ptr64:
4120 case tok::kw___ptr32:
4121 case tok::kw___w64:
4122 case tok::kw___cdecl:
4123 case tok::kw___stdcall:
4124 case tok::kw___fastcall:
4125 case tok::kw___thiscall:
4126 case tok::kw___regcall:
4127 case tok::kw___vectorcall:
4128 ParseMicrosoftTypeAttributes(DS.getAttributes());
4129 continue;
4130
4131 case tok::kw___funcref:
4132 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
4133 continue;
4134
4135 // Borland single token adornments.
4136 case tok::kw___pascal:
4137 ParseBorlandTypeAttributes(DS.getAttributes());
4138 continue;
4139
4140 // OpenCL single token adornments.
4141 case tok::kw___kernel:
4142 ParseOpenCLKernelAttributes(DS.getAttributes());
4143 continue;
4144
4145 // CUDA/HIP single token adornments.
4146 case tok::kw___noinline__:
4147 ParseCUDAFunctionAttributes(DS.getAttributes());
4148 continue;
4149
4150 // Nullability type specifiers.
4151 case tok::kw__Nonnull:
4152 case tok::kw__Nullable:
4153 case tok::kw__Nullable_result:
4154 case tok::kw__Null_unspecified:
4155 ParseNullabilityTypeSpecifiers(DS.getAttributes());
4156 continue;
4157
4158 // Objective-C 'kindof' types.
4159 case tok::kw___kindof:
4160 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
4161 nullptr, 0, tok::kw___kindof);
4162 (void)ConsumeToken();
4163 continue;
4164
4165 // storage-class-specifier
4166 case tok::kw_typedef:
4168 PrevSpec, DiagID, Policy);
4169 isStorageClass = true;
4170 break;
4171 case tok::kw_extern:
4173 Diag(Tok, diag::ext_thread_before) << "extern";
4175 PrevSpec, DiagID, Policy);
4176 isStorageClass = true;
4177 break;
4178 case tok::kw___private_extern__:
4180 Loc, PrevSpec, DiagID, Policy);
4181 isStorageClass = true;
4182 break;
4183 case tok::kw_static:
4185 Diag(Tok, diag::ext_thread_before) << "static";
4187 PrevSpec, DiagID, Policy);
4188 isStorageClass = true;
4189 break;
4190 case tok::kw_auto:
4191 if (getLangOpts().CPlusPlus11 || getLangOpts().C23) {
4192 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
4194 PrevSpec, DiagID, Policy);
4195 if (!isInvalid && !getLangOpts().C23)
4196 Diag(Tok, diag::ext_auto_storage_class)
4198 } else
4199 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
4200 DiagID, Policy);
4201 } else
4203 PrevSpec, DiagID, Policy);
4204 isStorageClass = true;
4205 break;
4206 case tok::kw___auto_type:
4207 Diag(Tok, diag::ext_auto_type);
4209 DiagID, Policy);
4210 break;
4211 case tok::kw_register:
4213 PrevSpec, DiagID, Policy);
4214 isStorageClass = true;
4215 break;
4216 case tok::kw_mutable:
4218 PrevSpec, DiagID, Policy);
4219 isStorageClass = true;
4220 break;
4221 case tok::kw___thread:
4223 PrevSpec, DiagID);
4224 isStorageClass = true;
4225 break;
4226 case tok::kw_thread_local:
4227 if (getLangOpts().C23)
4228 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4229 // We map thread_local to _Thread_local in C23 mode so it retains the C
4230 // semantics rather than getting the C++ semantics.
4231 // FIXME: diagnostics will show _Thread_local when the user wrote
4232 // thread_local in source in C23 mode; we need some general way to
4233 // identify which way the user spelled the keyword in source.
4237 Loc, PrevSpec, DiagID);
4238 isStorageClass = true;
4239 break;
4240 case tok::kw__Thread_local:
4241 diagnoseUseOfC11Keyword(Tok);
4243 Loc, PrevSpec, DiagID);
4244 isStorageClass = true;
4245 break;
4246
4247 // function-specifier
4248 case tok::kw_inline:
4249 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
4250 break;
4251 case tok::kw_virtual:
4252 // C++ for OpenCL does not allow virtual function qualifier, to avoid
4253 // function pointers restricted in OpenCL v2.0 s6.9.a.
4254 if (getLangOpts().OpenCLCPlusPlus &&
4255 !getActions().getOpenCLOptions().isAvailableOption(
4256 "__cl_clang_function_pointers", getLangOpts())) {
4257 DiagID = diag::err_openclcxx_virtual_function;
4258 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4259 isInvalid = true;
4260 } else {
4261 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
4262 }
4263 break;
4264 case tok::kw_explicit: {
4265 SourceLocation ExplicitLoc = Loc;
4266 SourceLocation CloseParenLoc;
4268 ConsumedEnd = ExplicitLoc;
4269 ConsumeToken(); // kw_explicit
4270 if (Tok.is(tok::l_paren)) {
4271 if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
4273 ? diag::warn_cxx17_compat_explicit_bool
4274 : diag::ext_explicit_bool);
4275
4276 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
4277 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4278 Tracker.consumeOpen();
4279
4280 EnterExpressionEvaluationContext ConstantEvaluated(
4282
4284 ConsumedEnd = Tok.getLocation();
4285 if (ExplicitExpr.isUsable()) {
4286 CloseParenLoc = Tok.getLocation();
4287 Tracker.consumeClose();
4288 ExplicitSpec =
4289 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
4290 } else
4291 Tracker.skipToEnd();
4292 } else {
4293 Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
4294 }
4295 }
4296 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
4297 ExplicitSpec, CloseParenLoc);
4298 break;
4299 }
4300 case tok::kw__Noreturn:
4301 diagnoseUseOfC11Keyword(Tok);
4302 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
4303 break;
4304
4305 // friend
4306 case tok::kw_friend:
4307 if (DSContext == DeclSpecContext::DSC_class)
4308 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
4309 else {
4310 PrevSpec = ""; // not actually used by the diagnostic
4311 DiagID = diag::err_friend_invalid_in_context;
4312 isInvalid = true;
4313 }
4314 break;
4315
4316 // Modules
4317 case tok::kw___module_private__:
4318 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
4319 break;
4320
4321 // constexpr, consteval, constinit specifiers
4322 case tok::kw_constexpr:
4323 if (getLangOpts().C23)
4324 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4326 PrevSpec, DiagID);
4327 break;
4328 case tok::kw_consteval:
4330 PrevSpec, DiagID);
4331 break;
4332 case tok::kw_constinit:
4334 PrevSpec, DiagID);
4335 break;
4336
4337 // type-specifier
4338 case tok::kw_short:
4340 DiagID, Policy);
4341 break;
4342 case tok::kw_long:
4345 DiagID, Policy);
4346 else
4348 PrevSpec, DiagID, Policy);
4349 break;
4350 case tok::kw___int64:
4352 PrevSpec, DiagID, Policy);
4353 break;
4354 case tok::kw_signed:
4355 isInvalid =
4356 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4357 break;
4358 case tok::kw_unsigned:
4360 DiagID);
4361 break;
4362 case tok::kw__Complex:
4363 if (!getLangOpts().C99)
4364 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4366 DiagID);
4367 break;
4368 case tok::kw__Imaginary:
4369 if (!getLangOpts().C99)
4370 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4372 DiagID);
4373 break;
4374 case tok::kw_void:
4375 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
4376 DiagID, Policy);
4377 break;
4378 case tok::kw_char:
4379 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
4380 DiagID, Policy);
4381 break;
4382 case tok::kw_int:
4383 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
4384 DiagID, Policy);
4385 break;
4386 case tok::kw__ExtInt:
4387 case tok::kw__BitInt: {
4388 DiagnoseBitIntUse(Tok);
4389 ExprResult ER = ParseExtIntegerArgument();
4390 if (ER.isInvalid())
4391 continue;
4392 isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
4393 ConsumedEnd = PrevTokLocation;
4394 break;
4395 }
4396 case tok::kw___int128:
4398 DiagID, Policy);
4399 break;
4400 case tok::kw_half:
4401 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
4402 DiagID, Policy);
4403 break;
4404 case tok::kw___bf16:
4406 DiagID, Policy);
4407 break;
4408 case tok::kw_float:
4409 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
4410 DiagID, Policy);
4411 break;
4412 case tok::kw_double:
4414 DiagID, Policy);
4415 break;
4416 case tok::kw__Float16:
4418 DiagID, Policy);
4419 break;
4420 case tok::kw__Accum:
4421 assert(getLangOpts().FixedPoint &&
4422 "This keyword is only used when fixed point types are enabled "
4423 "with `-ffixed-point`");
4424 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec, DiagID,
4425 Policy);
4426 break;
4427 case tok::kw__Fract:
4428 assert(getLangOpts().FixedPoint &&
4429 "This keyword is only used when fixed point types are enabled "
4430 "with `-ffixed-point`");
4431 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec, DiagID,
4432 Policy);
4433 break;
4434 case tok::kw__Sat:
4435 assert(getLangOpts().FixedPoint &&
4436 "This keyword is only used when fixed point types are enabled "
4437 "with `-ffixed-point`");
4438 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
4439 break;
4440 case tok::kw___float128:
4442 DiagID, Policy);
4443 break;
4444 case tok::kw___ibm128:
4446 DiagID, Policy);
4447 break;
4448 case tok::kw_wchar_t:
4449 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
4450 DiagID, Policy);
4451 break;
4452 case tok::kw_char8_t:
4453 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
4454 DiagID, Policy);
4455 break;
4456 case tok::kw_char16_t:
4458 DiagID, Policy);
4459 break;
4460 case tok::kw_char32_t:
4462 DiagID, Policy);
4463 break;
4464 case tok::kw_bool:
4465 if (getLangOpts().C23)
4466 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4467 [[fallthrough]];
4468 case tok::kw__Bool:
4469 if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
4470 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4471
4472 if (Tok.is(tok::kw_bool) &&
4475 PrevSpec = ""; // Not used by the diagnostic.
4476 DiagID = diag::err_bool_redeclaration;
4477 // For better error recovery.
4478 Tok.setKind(tok::identifier);
4479 isInvalid = true;
4480 } else {
4481 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
4482 DiagID, Policy);
4483 }
4484 break;
4485 case tok::kw__Decimal32:
4487 DiagID, Policy);
4488 break;
4489 case tok::kw__Decimal64:
4491 DiagID, Policy);
4492 break;
4493 case tok::kw__Decimal128:
4495 DiagID, Policy);
4496 break;
4497 case tok::kw___vector:
4498 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4499 break;
4500 case tok::kw___pixel:
4501 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4502 break;
4503 case tok::kw___bool:
4504 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4505 break;
4506 case tok::kw_pipe:
4507 if (!getLangOpts().OpenCL ||
4508 getLangOpts().getOpenCLCompatibleVersion() < 200) {
4509 // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4510 // should support the "pipe" word as identifier.
4512 Tok.setKind(tok::identifier);
4513 goto DoneWithDeclSpec;
4514 } else if (!getLangOpts().OpenCLPipes) {
4515 DiagID = diag::err_opencl_unknown_type_specifier;
4516 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4517 isInvalid = true;
4518 } else
4519 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4520 break;
4521// We only need to enumerate each image type once.
4522#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4523#define IMAGE_WRITE_TYPE(Type, Id, Ext)
4524#define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4525 case tok::kw_##ImgType##_t: \
4526 if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4527 goto DoneWithDeclSpec; \
4528 break;
4529#include "clang/Basic/OpenCLImageTypes.def"
4530 case tok::kw___unknown_anytype:
4532 PrevSpec, DiagID, Policy);
4533 break;
4534
4535 // class-specifier:
4536 case tok::kw_class:
4537 case tok::kw_struct:
4538 case tok::kw___interface:
4539 case tok::kw_union: {
4540 tok::TokenKind Kind = Tok.getKind();
4541 ConsumeToken();
4542
4543 // These are attributes following class specifiers.
4544 // To produce better diagnostic, we parse them when
4545 // parsing class specifier.
4546 ParsedAttributes Attributes(AttrFactory);
4547 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4548 EnteringContext, DSContext, Attributes);
4549
4550 // If there are attributes following class specifier,
4551 // take them over and handle them here.
4552 if (!Attributes.empty()) {
4553 AttrsLastTime = true;
4554 attrs.takeAllFrom(Attributes);
4555 }
4556 continue;
4557 }
4558
4559 // enum-specifier:
4560 case tok::kw_enum:
4561 ConsumeToken();
4562 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4563 continue;
4564
4565 // cv-qualifier:
4566 case tok::kw_const:
4567 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4568 getLangOpts());
4569 break;
4570 case tok::kw_volatile:
4571 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4572 getLangOpts());
4573 break;
4574 case tok::kw_restrict:
4575 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4576 getLangOpts());
4577 break;
4578
4579 // C++ typename-specifier:
4580 case tok::kw_typename:
4582 DS.SetTypeSpecError();
4583 goto DoneWithDeclSpec;
4584 }
4585 if (!Tok.is(tok::kw_typename))
4586 continue;
4587 break;
4588
4589 // C23/GNU typeof support.
4590 case tok::kw_typeof:
4591 case tok::kw_typeof_unqual:
4592 ParseTypeofSpecifier(DS);
4593 continue;
4594
4595 case tok::annot_decltype:
4596 ParseDecltypeSpecifier(DS);
4597 continue;
4598
4599 case tok::annot_pack_indexing_type:
4600 ParsePackIndexingType(DS);
4601 continue;
4602
4603 case tok::annot_pragma_pack:
4604 HandlePragmaPack();
4605 continue;
4606
4607 case tok::annot_pragma_ms_pragma:
4608 HandlePragmaMSPragma();
4609 continue;
4610
4611 case tok::annot_pragma_ms_vtordisp:
4612 HandlePragmaMSVtorDisp();
4613 continue;
4614
4615 case tok::annot_pragma_ms_pointers_to_members:
4616 HandlePragmaMSPointersToMembers();
4617 continue;
4618
4619#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
4620#include "clang/Basic/TransformTypeTraits.def"
4621 // HACK: libstdc++ already uses '__remove_cv' as an alias template so we
4622 // work around this by expecting all transform type traits to be suffixed
4623 // with '('. They're an identifier otherwise.
4624 if (!MaybeParseTypeTransformTypeSpecifier(DS))
4625 goto ParseIdentifier;
4626 continue;
4627
4628 case tok::kw__Atomic:
4629 // C11 6.7.2.4/4:
4630 // If the _Atomic keyword is immediately followed by a left parenthesis,
4631 // it is interpreted as a type specifier (with a type name), not as a
4632 // type qualifier.
4633 diagnoseUseOfC11Keyword(Tok);
4634 if (NextToken().is(tok::l_paren)) {
4635 ParseAtomicSpecifier(DS);
4636 continue;
4637 }
4638 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4639 getLangOpts());
4640 break;
4641
4642 // OpenCL address space qualifiers:
4643 case tok::kw___generic:
4644 // generic address space is introduced only in OpenCL v2.0
4645 // see OpenCL C Spec v2.0 s6.5.5
4646 // OpenCL v3.0 introduces __opencl_c_generic_address_space
4647 // feature macro to indicate if generic address space is supported
4648 if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4649 DiagID = diag::err_opencl_unknown_type_specifier;
4650 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4651 isInvalid = true;
4652 break;
4653 }
4654 [[fallthrough]];
4655 case tok::kw_private:
4656 // It's fine (but redundant) to check this for __generic on the
4657 // fallthrough path; we only form the __generic token in OpenCL mode.
4658 if (!getLangOpts().OpenCL)
4659 goto DoneWithDeclSpec;
4660 [[fallthrough]];
4661 case tok::kw___private:
4662 case tok::kw___global:
4663 case tok::kw___local:
4664 case tok::kw___constant:
4665 // OpenCL access qualifiers:
4666 case tok::kw___read_only:
4667 case tok::kw___write_only:
4668 case tok::kw___read_write:
4669 ParseOpenCLQualifiers(DS.getAttributes());
4670 break;
4671
4672 case tok::kw_groupshared:
4673 case tok::kw_in:
4674 case tok::kw_inout:
4675 case tok::kw_out:
4676 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4677 ParseHLSLQualifiers(DS.getAttributes());
4678 continue;
4679
4680 case tok::less:
4681 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4682 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4683 // but we support it.
4684 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4685 goto DoneWithDeclSpec;
4686
4687 SourceLocation StartLoc = Tok.getLocation();
4688 SourceLocation EndLoc;
4689 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4690 if (Type.isUsable()) {
4691 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4692 PrevSpec, DiagID, Type.get(),
4693 Actions.getASTContext().getPrintingPolicy()))
4694 Diag(StartLoc, DiagID) << PrevSpec;
4695
4696 DS.SetRangeEnd(EndLoc);
4697 } else {
4698 DS.SetTypeSpecError();
4699 }
4700
4701 // Need to support trailing type qualifiers (e.g. "id<p> const").
4702 // If a type specifier follows, it will be diagnosed elsewhere.
4703 continue;
4704 }
4705
4706 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4707
4708 // If the specifier wasn't legal, issue a diagnostic.
4709 if (isInvalid) {
4710 assert(PrevSpec && "Method did not return previous specifier!");
4711 assert(DiagID);
4712
4713 if (DiagID == diag::ext_duplicate_declspec ||
4714 DiagID == diag::ext_warn_duplicate_declspec ||
4715 DiagID == diag::err_duplicate_declspec)
4716 Diag(Loc, DiagID) << PrevSpec
4718 SourceRange(Loc, DS.getEndLoc()));
4719 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4720 Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4721 << isStorageClass;
4722 } else
4723 Diag(Loc, DiagID) << PrevSpec;
4724 }
4725
4726 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4727 // After an error the next token can be an annotation token.
4729
4730 AttrsLastTime = false;
4731 }
4732}
4733
4735 Parser &P) {
4736
4738 return;
4739
4740 auto *RD = dyn_cast<RecordDecl>(DS.getRepAsDecl());
4741 // We're only interested in unnamed, non-anonymous struct
4742 if (!RD || !RD->getName().empty() || RD->isAnonymousStructOrUnion())
4743 return;
4744
4745 for (auto *I : RD->decls()) {
4746 auto *VD = dyn_cast<ValueDecl>(I);
4747 if (!VD)
4748 continue;
4749
4750 auto *CAT = VD->getType()->getAs<CountAttributedType>();
4751 if (!CAT)
4752 continue;
4753
4754 for (const auto &DD : CAT->dependent_decls()) {
4755 if (!RD->containsDecl(DD.getDecl())) {
4756 P.Diag(VD->getBeginLoc(),
4757 diag::err_flexible_array_count_not_in_same_struct)
4758 << DD.getDecl();
4759 P.Diag(DD.getDecl()->getBeginLoc(),
4760 diag::note_flexible_array_counted_by_attr_field)
4761 << DD.getDecl();
4762 }
4763 }
4764 }
4765}
4766
4767/// ParseStructDeclaration - Parse a struct declaration without the terminating
4768/// semicolon.
4769///
4770/// Note that a struct declaration refers to a declaration in a struct,
4771/// not to the declaration of a struct.
4772///
4773/// struct-declaration:
4774/// [C23] attributes-specifier-seq[opt]
4775/// specifier-qualifier-list struct-declarator-list
4776/// [GNU] __extension__ struct-declaration
4777/// [GNU] specifier-qualifier-list
4778/// struct-declarator-list:
4779/// struct-declarator
4780/// struct-declarator-list ',' struct-declarator
4781/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4782/// struct-declarator:
4783/// declarator
4784/// [GNU] declarator attributes[opt]
4785/// declarator[opt] ':' constant-expression
4786/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4787///
4788void Parser::ParseStructDeclaration(
4789 ParsingDeclSpec &DS,
4790 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4791
4792 if (Tok.is(tok::kw___extension__)) {
4793 // __extension__ silences extension warnings in the subexpression.
4794 ExtensionRAIIObject O(Diags); // Use RAII to do this.
4795 ConsumeToken();
4796 return ParseStructDeclaration(DS, FieldsCallback);
4797 }
4798
4799 // Parse leading attributes.
4800 ParsedAttributes Attrs(AttrFactory);
4801 MaybeParseCXX11Attributes(Attrs);
4802
4803 // Parse the common specifier-qualifiers-list piece.
4804 ParseSpecifierQualifierList(DS);
4805
4806 // If there are no declarators, this is a free-standing declaration
4807 // specifier. Let the actions module cope with it.
4808 if (Tok.is(tok::semi)) {
4809 // C23 6.7.2.1p9 : "The optional attribute specifier sequence in a
4810 // member declaration appertains to each of the members declared by the
4811 // member declarator list; it shall not appear if the optional member
4812 // declarator list is omitted."
4813 ProhibitAttributes(Attrs);
4814 RecordDecl *AnonRecord = nullptr;
4815 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
4816 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
4817 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4818 DS.complete(TheDecl);
4819 return;
4820 }
4821
4822 // Read struct-declarators until we find the semicolon.
4823 bool FirstDeclarator = true;
4824 SourceLocation CommaLoc;
4825 while (true) {
4826 ParsingFieldDeclarator DeclaratorInfo(*this, DS, Attrs);
4827 DeclaratorInfo.D.setCommaLoc(CommaLoc);
4828
4829 // Attributes are only allowed here on successive declarators.
4830 if (!FirstDeclarator) {
4831 // However, this does not apply for [[]] attributes (which could show up
4832 // before or after the __attribute__ attributes).
4833 DiagnoseAndSkipCXX11Attributes();
4834 MaybeParseGNUAttributes(DeclaratorInfo.D);
4835 DiagnoseAndSkipCXX11Attributes();
4836 }
4837
4838 /// struct-declarator: declarator
4839 /// struct-declarator: declarator[opt] ':' constant-expression
4840 if (Tok.isNot(tok::colon)) {
4841 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4843 ParseDeclarator(DeclaratorInfo.D);
4844 } else
4845 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4846
4847 // Here, we now know that the unnamed struct is not an anonymous struct.
4848 // Report an error if a counted_by attribute refers to a field in a
4849 // different named struct.
4851
4852 if (TryConsumeToken(tok::colon)) {
4854 if (Res.isInvalid())
4855 SkipUntil(tok::semi, StopBeforeMatch);
4856 else
4857 DeclaratorInfo.BitfieldSize = Res.get();
4858 }
4859
4860 // If attributes exist after the declarator, parse them.
4861 MaybeParseGNUAttributes(DeclaratorInfo.D);
4862
4863 // We're done with this declarator; invoke the callback.
4864 FieldsCallback(DeclaratorInfo);
4865
4866 // If we don't have a comma, it is either the end of the list (a ';')
4867 // or an error, bail out.
4868 if (!TryConsumeToken(tok::comma, CommaLoc))
4869 return;
4870
4871 FirstDeclarator = false;
4872 }
4873}
4874
4875/// ParseStructUnionBody
4876/// struct-contents:
4877/// struct-declaration-list
4878/// [EXT] empty
4879/// [GNU] "struct-declaration-list" without terminating ';'
4880/// struct-declaration-list:
4881/// struct-declaration
4882/// struct-declaration-list struct-declaration
4883/// [OBC] '@' 'defs' '(' class-name ')'
4884///
4885void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4888 "parsing struct/union body");
4889 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4890
4891 BalancedDelimiterTracker T(*this, tok::l_brace);
4892 if (T.consumeOpen())
4893 return;
4894
4895 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4897
4898 // While we still have something to read, read the declarations in the struct.
4899 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4900 Tok.isNot(tok::eof)) {
4901 // Each iteration of this loop reads one struct-declaration.
4902
4903 // Check for extraneous top-level semicolon.
4904 if (Tok.is(tok::semi)) {
4905 ConsumeExtraSemi(InsideStruct, TagType);
4906 continue;
4907 }
4908
4909 // Parse _Static_assert declaration.
4910 if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
4911 SourceLocation DeclEnd;
4912 ParseStaticAssertDeclaration(DeclEnd);
4913 continue;
4914 }
4915
4916 if (Tok.is(tok::annot_pragma_pack)) {
4917 HandlePragmaPack();
4918 continue;
4919 }
4920
4921 if (Tok.is(tok::annot_pragma_align)) {
4922 HandlePragmaAlign();
4923 continue;
4924 }
4925
4926 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
4927 // Result can be ignored, because it must be always empty.
4929 ParsedAttributes Attrs(AttrFactory);
4930 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4931 continue;
4932 }
4933
4934 if (Tok.is(tok::annot_pragma_openacc)) {
4936 continue;
4937 }
4938
4939 if (tok::isPragmaAnnotation(Tok.getKind())) {
4940 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4943 ConsumeAnnotationToken();
4944 continue;
4945 }
4946
4947 if (!Tok.is(tok::at)) {
4948 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4949 // Install the declarator into the current TagDecl.
4950 Decl *Field =
4951 Actions.ActOnField(getCurScope(), TagDecl,
4952 FD.D.getDeclSpec().getSourceRange().getBegin(),
4953 FD.D, FD.BitfieldSize);
4954 FD.complete(Field);
4955 };
4956
4957 // Parse all the comma separated declarators.
4958 ParsingDeclSpec DS(*this);
4959 ParseStructDeclaration(DS, CFieldCallback);
4960 } else { // Handle @defs
4961 ConsumeToken();
4962 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4963 Diag(Tok, diag::err_unexpected_at);
4964 SkipUntil(tok::semi);
4965 continue;
4966 }
4967 ConsumeToken();
4968 ExpectAndConsume(tok::l_paren);
4969 if (!Tok.is(tok::identifier)) {
4970 Diag(Tok, diag::err_expected) << tok::identifier;
4971 SkipUntil(tok::semi);
4972 continue;
4973 }
4975 Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4976 Tok.getIdentifierInfo(), Fields);
4977 ConsumeToken();
4978 ExpectAndConsume(tok::r_paren);
4979 }
4980
4981 if (TryConsumeToken(tok::semi))
4982 continue;
4983
4984 if (Tok.is(tok::r_brace)) {
4985 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4986 break;
4987 }
4988
4989 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4990 // Skip to end of block or statement to avoid ext-warning on extra ';'.
4991 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4992 // If we stopped at a ';', eat it.
4993 TryConsumeToken(tok::semi);
4994 }
4995
4996 T.consumeClose();
4997
4998 ParsedAttributes attrs(AttrFactory);
4999 // If attributes exist after struct contents, parse them.
5000 MaybeParseGNUAttributes(attrs);
5001
5002 SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
5003
5004 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
5005 T.getOpenLocation(), T.getCloseLocation(), attrs);
5006 StructScope.Exit();
5007 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
5008}
5009
5010/// ParseEnumSpecifier
5011/// enum-specifier: [C99 6.7.2.2]
5012/// 'enum' identifier[opt] '{' enumerator-list '}'
5013///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
5014/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
5015/// '}' attributes[opt]
5016/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
5017/// '}'
5018/// 'enum' identifier
5019/// [GNU] 'enum' attributes[opt] identifier
5020///
5021/// [C++11] enum-head '{' enumerator-list[opt] '}'
5022/// [C++11] enum-head '{' enumerator-list ',' '}'
5023///
5024/// enum-head: [C++11]
5025/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
5026/// enum-key attribute-specifier-seq[opt] nested-name-specifier
5027/// identifier enum-base[opt]
5028///
5029/// enum-key: [C++11]
5030/// 'enum'
5031/// 'enum' 'class'
5032/// 'enum' 'struct'
5033///
5034/// enum-base: [C++11]
5035/// ':' type-specifier-seq
5036///
5037/// [C++] elaborated-type-specifier:
5038/// [C++] 'enum' nested-name-specifier[opt] identifier
5039///
5040void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
5041 const ParsedTemplateInfo &TemplateInfo,
5042 AccessSpecifier AS, DeclSpecContext DSC) {
5043 // Parse the tag portion of this.
5044 if (Tok.is(tok::code_completion)) {
5045 // Code completion for an enum name.
5046 cutOffParsing();
5048 DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
5049 return;
5050 }
5051
5052 // If attributes exist after tag, parse them.
5053 ParsedAttributes attrs(AttrFactory);
5054 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
5055
5056 SourceLocation ScopedEnumKWLoc;
5057 bool IsScopedUsingClassTag = false;
5058
5059 // In C++11, recognize 'enum class' and 'enum struct'.
5060 if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
5061 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
5062 : diag::ext_scoped_enum);
5063 IsScopedUsingClassTag = Tok.is(tok::kw_class);
5064 ScopedEnumKWLoc = ConsumeToken();
5065
5066 // Attributes are not allowed between these keywords. Diagnose,
5067 // but then just treat them like they appeared in the right place.
5068 ProhibitAttributes(attrs);
5069
5070 // They are allowed afterwards, though.
5071 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
5072 }
5073
5074 // C++11 [temp.explicit]p12:
5075 // The usual access controls do not apply to names used to specify
5076 // explicit instantiations.
5077 // We extend this to also cover explicit specializations. Note that
5078 // we don't suppress if this turns out to be an elaborated type
5079 // specifier.
5080 bool shouldDelayDiagsInTag =
5081 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
5082 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
5083 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
5084
5085 // Determine whether this declaration is permitted to have an enum-base.
5086 AllowDefiningTypeSpec AllowEnumSpecifier =
5087 isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus);
5088 bool CanBeOpaqueEnumDeclaration =
5089 DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
5090 bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
5091 getLangOpts().MicrosoftExt) &&
5092 (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
5093 CanBeOpaqueEnumDeclaration);
5094
5095 CXXScopeSpec &SS = DS.getTypeSpecScope();
5096 if (getLangOpts().CPlusPlus) {
5097 // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
5099
5100 CXXScopeSpec Spec;
5101 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
5102 /*ObjectHasErrors=*/false,
5103 /*EnteringContext=*/true))
5104 return;
5105
5106 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
5107 Diag(Tok, diag::err_expected) << tok::identifier;
5108 DS.SetTypeSpecError();
5109 if (Tok.isNot(tok::l_brace)) {
5110 // Has no name and is not a definition.
5111 // Skip the rest of this declarator, up until the comma or semicolon.
5112 SkipUntil(tok::comma, StopAtSemi);
5113 return;
5114 }
5115 }
5116
5117 SS = Spec;
5118 }
5119
5120 // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
5121 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
5122 Tok.isNot(tok::colon)) {
5123 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
5124
5125 DS.SetTypeSpecError();
5126 // Skip the rest of this declarator, up until the comma or semicolon.
5127 SkipUntil(tok::comma, StopAtSemi);
5128 return;
5129 }
5130
5131 // If an identifier is present, consume and remember it.
5132 IdentifierInfo *Name = nullptr;
5133 SourceLocation NameLoc;
5134 if (Tok.is(tok::identifier)) {
5135 Name = Tok.getIdentifierInfo();
5136 NameLoc = ConsumeToken();
5137 }
5138
5139 if (!Name && ScopedEnumKWLoc.isValid()) {
5140 // C++0x 7.2p2: The optional identifier shall not be omitted in the
5141 // declaration of a scoped enumeration.
5142 Diag(Tok, diag::err_scoped_enum_missing_identifier);
5143 ScopedEnumKWLoc = SourceLocation();
5144 IsScopedUsingClassTag = false;
5145 }
5146
5147 // Okay, end the suppression area. We'll decide whether to emit the
5148 // diagnostics in a second.
5149 if (shouldDelayDiagsInTag)
5150 diagsFromTag.done();
5151
5152 TypeResult BaseType;
5153 SourceRange BaseRange;
5154
5155 bool CanBeBitfield =
5156 getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
5157
5158 // Parse the fixed underlying type.
5159 if (Tok.is(tok::colon)) {
5160 // This might be an enum-base or part of some unrelated enclosing context.
5161 //
5162 // 'enum E : base' is permitted in two circumstances:
5163 //
5164 // 1) As a defining-type-specifier, when followed by '{'.
5165 // 2) As the sole constituent of a complete declaration -- when DS is empty
5166 // and the next token is ';'.
5167 //
5168 // The restriction to defining-type-specifiers is important to allow parsing
5169 // a ? new enum E : int{}
5170 // _Generic(a, enum E : int{})
5171 // properly.
5172 //
5173 // One additional consideration applies:
5174 //
5175 // C++ [dcl.enum]p1:
5176 // A ':' following "enum nested-name-specifier[opt] identifier" within
5177 // the decl-specifier-seq of a member-declaration is parsed as part of
5178 // an enum-base.
5179 //
5180 // Other language modes supporting enumerations with fixed underlying types
5181 // do not have clear rules on this, so we disambiguate to determine whether
5182 // the tokens form a bit-field width or an enum-base.
5183
5184 if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
5185 // Outside C++11, do not interpret the tokens as an enum-base if they do
5186 // not make sense as one. In C++11, it's an error if this happens.
5188 Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
5189 } else if (CanHaveEnumBase || !ColonIsSacred) {
5190 SourceLocation ColonLoc = ConsumeToken();
5191
5192 // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
5193 // because under -fms-extensions,
5194 // enum E : int *p;
5195 // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
5196 DeclSpec DS(AttrFactory);
5197 // enum-base is not assumed to be a type and therefore requires the
5198 // typename keyword [p0634r3].
5199 ParseSpecifierQualifierList(DS, ImplicitTypenameContext::No, AS,
5200 DeclSpecContext::DSC_type_specifier);
5201 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
5203 BaseType = Actions.ActOnTypeName(DeclaratorInfo);
5204
5205 BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
5206
5207 if (!getLangOpts().ObjC && !getLangOpts().C23) {
5209 Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
5210 << BaseRange;
5211 else if (getLangOpts().CPlusPlus)
5212 Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
5213 << BaseRange;
5214 else if (getLangOpts().MicrosoftExt)
5215 Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
5216 << BaseRange;
5217 else
5218 Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
5219 << BaseRange;
5220 }
5221 }
5222 }
5223
5224 // There are four options here. If we have 'friend enum foo;' then this is a
5225 // friend declaration, and cannot have an accompanying definition. If we have
5226 // 'enum foo;', then this is a forward declaration. If we have
5227 // 'enum foo {...' then this is a definition. Otherwise we have something
5228 // like 'enum foo xyz', a reference.
5229 //
5230 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
5231 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
5232 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
5233 //
5234 Sema::TagUseKind TUK;
5235 if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
5236 TUK = Sema::TUK_Reference;
5237 else if (Tok.is(tok::l_brace)) {
5238 if (DS.isFriendSpecified()) {
5239 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
5241 ConsumeBrace();
5242 SkipUntil(tok::r_brace, StopAtSemi);
5243 // Discard any other definition-only pieces.
5244 attrs.clear();
5245 ScopedEnumKWLoc = SourceLocation();
5246 IsScopedUsingClassTag = false;
5247 BaseType = TypeResult();
5248 TUK = Sema::TUK_Friend;
5249 } else {
5251 }
5252 } else if (!isTypeSpecifier(DSC) &&
5253 (Tok.is(tok::semi) ||
5254 (Tok.isAtStartOfLine() &&
5255 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
5256 // An opaque-enum-declaration is required to be standalone (no preceding or
5257 // following tokens in the declaration). Sema enforces this separately by
5258 // diagnosing anything else in the DeclSpec.
5260 if (Tok.isNot(tok::semi)) {
5261 // A semicolon was missing after this declaration. Diagnose and recover.
5262 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5263 PP.EnterToken(Tok, /*IsReinject=*/true);
5264 Tok.setKind(tok::semi);
5265 }
5266 } else {
5267 TUK = Sema::TUK_Reference;
5268 }
5269
5270 bool IsElaboratedTypeSpecifier =
5271 TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend;
5272
5273 // If this is an elaborated type specifier nested in a larger declaration,
5274 // and we delayed diagnostics before, just merge them into the current pool.
5275 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
5276 diagsFromTag.redelay();
5277 }
5278
5279 MultiTemplateParamsArg TParams;
5280 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
5281 TUK != Sema::TUK_Reference) {
5282 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
5283 // Skip the rest of this declarator, up until the comma or semicolon.
5284 Diag(Tok, diag::err_enum_template);
5285 SkipUntil(tok::comma, StopAtSemi);
5286 return;
5287 }
5288
5289 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
5290 // Enumerations can't be explicitly instantiated.
5291 DS.SetTypeSpecError();
5292 Diag(StartLoc, diag::err_explicit_instantiation_enum);
5293 return;
5294 }
5295
5296 assert(TemplateInfo.TemplateParams && "no template parameters");
5297 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
5298 TemplateInfo.TemplateParams->size());
5299 SS.setTemplateParamLists(TParams);
5300 }
5301
5302 if (!Name && TUK != Sema::TUK_Definition) {
5303 Diag(Tok, diag::err_enumerator_unnamed_no_def);
5304
5305 DS.SetTypeSpecError();
5306 // Skip the rest of this declarator, up until the comma or semicolon.
5307 SkipUntil(tok::comma, StopAtSemi);
5308 return;
5309 }
5310
5311 // An elaborated-type-specifier has a much more constrained grammar:
5312 //
5313 // 'enum' nested-name-specifier[opt] identifier
5314 //
5315 // If we parsed any other bits, reject them now.
5316 //
5317 // MSVC and (for now at least) Objective-C permit a full enum-specifier
5318 // or opaque-enum-declaration anywhere.
5319 if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
5320 !getLangOpts().ObjC) {
5321 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
5322 diag::err_keyword_not_allowed,
5323 /*DiagnoseEmptyAttrs=*/true);
5324 if (BaseType.isUsable())
5325 Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
5326 << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
5327 else if (ScopedEnumKWLoc.isValid())
5328 Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
5329 << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
5330 }
5331
5332 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
5333
5334 SkipBodyInfo SkipBody;
5335 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
5336 NextToken().is(tok::identifier))
5337 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
5338 NextToken().getIdentifierInfo(),
5339 NextToken().getLocation());
5340
5341 bool Owned = false;
5342 bool IsDependent = false;
5343 const char *PrevSpec = nullptr;
5344 unsigned DiagID;
5345 Decl *TagDecl =
5346 Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS,
5347 Name, NameLoc, attrs, AS, DS.getModulePrivateSpecLoc(),
5348 TParams, Owned, IsDependent, ScopedEnumKWLoc,
5349 IsScopedUsingClassTag,
5350 BaseType, DSC == DeclSpecContext::DSC_type_specifier,
5351 DSC == DeclSpecContext::DSC_template_param ||
5352 DSC == DeclSpecContext::DSC_template_type_arg,
5353 OffsetOfState, &SkipBody).get();
5354
5355 if (SkipBody.ShouldSkip) {
5356 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
5357
5358 BalancedDelimiterTracker T(*this, tok::l_brace);
5359 T.consumeOpen();
5360 T.skipToEnd();
5361
5362 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5363 NameLoc.isValid() ? NameLoc : StartLoc,
5364 PrevSpec, DiagID, TagDecl, Owned,
5365 Actions.getASTContext().getPrintingPolicy()))
5366 Diag(StartLoc, DiagID) << PrevSpec;
5367 return;
5368 }
5369
5370 if (IsDependent) {
5371 // This enum has a dependent nested-name-specifier. Handle it as a
5372 // dependent tag.
5373 if (!Name) {
5374 DS.SetTypeSpecError();
5375 Diag(Tok, diag::err_expected_type_name_after_typename);
5376 return;
5377 }
5378
5380 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
5381 if (Type.isInvalid()) {
5382 DS.SetTypeSpecError();
5383 return;
5384 }
5385
5386 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
5387 NameLoc.isValid() ? NameLoc : StartLoc,
5388 PrevSpec, DiagID, Type.get(),
5389 Actions.getASTContext().getPrintingPolicy()))
5390 Diag(StartLoc, DiagID) << PrevSpec;
5391
5392 return;
5393 }
5394
5395 if (!TagDecl) {
5396 // The action failed to produce an enumeration tag. If this is a
5397 // definition, consume the entire definition.
5398 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
5399 ConsumeBrace();
5400 SkipUntil(tok::r_brace, StopAtSemi);
5401 }
5402
5403 DS.SetTypeSpecError();
5404 return;
5405 }
5406
5407 if (Tok.is(tok::l_brace) && TUK == Sema::TUK_Definition) {
5408 Decl *D = SkipBody.CheckSameAsPrevi