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