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