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 requires parsing its arguments
372/// in an unevaluated context or not.
374#define CLANG_ATTR_ARG_CONTEXT_LIST
375 return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
376#include "clang/Parse/AttrParserStringSwitches.inc"
377 .Default(false);
378#undef CLANG_ATTR_ARG_CONTEXT_LIST
379}
380
381IdentifierLoc *Parser::ParseIdentifierLoc() {
382 assert(Tok.is(tok::identifier) && "expected an identifier");
384 Tok.getLocation(),
385 Tok.getIdentifierInfo());
386 ConsumeToken();
387 return IL;
388}
389
390void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
391 SourceLocation AttrNameLoc,
392 ParsedAttributes &Attrs,
393 IdentifierInfo *ScopeName,
394 SourceLocation ScopeLoc,
395 ParsedAttr::Form Form) {
396 BalancedDelimiterTracker Parens(*this, tok::l_paren);
397 Parens.consumeOpen();
398
400 if (Tok.isNot(tok::r_paren))
401 T = ParseTypeName();
402
403 if (Parens.consumeClose())
404 return;
405
406 if (T.isInvalid())
407 return;
408
409 if (T.isUsable())
410 Attrs.addNewTypeAttr(&AttrName,
411 SourceRange(AttrNameLoc, Parens.getCloseLocation()),
412 ScopeName, ScopeLoc, T.get(), Form);
413 else
414 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
415 ScopeName, ScopeLoc, nullptr, 0, Form);
416}
417
419Parser::ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName) {
420 if (Tok.is(tok::l_paren)) {
421 BalancedDelimiterTracker Paren(*this, tok::l_paren);
422 Paren.consumeOpen();
423 ExprResult Res = ParseUnevaluatedStringInAttribute(AttrName);
424 Paren.consumeClose();
425 return Res;
426 }
427 if (!isTokenStringLiteral()) {
428 Diag(Tok.getLocation(), diag::err_expected_string_literal)
429 << /*in attribute...*/ 4 << AttrName.getName();
430 return ExprError();
431 }
433}
434
435bool Parser::ParseAttributeArgumentList(
436 const IdentifierInfo &AttrName, SmallVectorImpl<Expr *> &Exprs,
437 ParsedAttributeArgumentsProperties ArgsProperties) {
438 bool SawError = false;
439 unsigned Arg = 0;
440 while (true) {
442 if (ArgsProperties.isStringLiteralArg(Arg)) {
443 Expr = ParseUnevaluatedStringInAttribute(AttrName);
444 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
445 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
446 Expr = ParseBraceInitializer();
447 } else {
449 }
451
452 if (Tok.is(tok::ellipsis))
453 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
454 else if (Tok.is(tok::code_completion)) {
455 // There's nothing to suggest in here as we parsed a full expression.
456 // Instead fail and propagate the error since caller might have something
457 // the suggest, e.g. signature help in function call. Note that this is
458 // performed before pushing the \p Expr, so that signature help can report
459 // current argument correctly.
460 SawError = true;
461 cutOffParsing();
462 break;
463 }
464
465 if (Expr.isInvalid()) {
466 SawError = true;
467 break;
468 }
469
470 Exprs.push_back(Expr.get());
471
472 if (Tok.isNot(tok::comma))
473 break;
474 // Move to the next argument, remember where the comma was.
475 Token Comma = Tok;
476 ConsumeToken();
477 checkPotentialAngleBracketDelimiter(Comma);
478 Arg++;
479 }
480
481 if (SawError) {
482 // Ensure typos get diagnosed when errors were encountered while parsing the
483 // expression list.
484 for (auto &E : Exprs) {
486 if (Expr.isUsable())
487 E = Expr.get();
488 }
489 }
490 return SawError;
491}
492
493unsigned Parser::ParseAttributeArgsCommon(
494 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
495 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
496 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
497 // Ignore the left paren location for now.
498 ConsumeParen();
499
500 bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
501 bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
502 bool AttributeHasVariadicIdentifierArg =
504
505 // Interpret "kw_this" as an identifier if the attributed requests it.
506 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
507 Tok.setKind(tok::identifier);
508
509 ArgsVector ArgExprs;
510 if (Tok.is(tok::identifier)) {
511 // If this attribute wants an 'identifier' argument, make it so.
512 bool IsIdentifierArg = AttributeHasVariadicIdentifierArg ||
513 attributeHasIdentifierArg(*AttrName);
514 ParsedAttr::Kind AttrKind =
515 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
516
517 // If we don't know how to parse this attribute, but this is the only
518 // token in this argument, assume it's meant to be an identifier.
519 if (AttrKind == ParsedAttr::UnknownAttribute ||
520 AttrKind == ParsedAttr::IgnoredAttribute) {
521 const Token &Next = NextToken();
522 IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
523 }
524
525 if (IsIdentifierArg)
526 ArgExprs.push_back(ParseIdentifierLoc());
527 }
528
529 ParsedType TheParsedType;
530 if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
531 // Eat the comma.
532 if (!ArgExprs.empty())
533 ConsumeToken();
534
535 if (AttributeIsTypeArgAttr) {
536 // FIXME: Multiple type arguments are not implemented.
538 if (T.isInvalid()) {
539 SkipUntil(tok::r_paren, StopAtSemi);
540 return 0;
541 }
542 if (T.isUsable())
543 TheParsedType = T.get();
544 } else if (AttributeHasVariadicIdentifierArg) {
545 // Parse variadic identifier arg. This can either consume identifiers or
546 // expressions. Variadic identifier args do not support parameter packs
547 // because those are typically used for attributes with enumeration
548 // arguments, and those enumerations are not something the user could
549 // express via a pack.
550 do {
551 // Interpret "kw_this" as an identifier if the attributed requests it.
552 if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
553 Tok.setKind(tok::identifier);
554
555 ExprResult ArgExpr;
556 if (Tok.is(tok::identifier)) {
557 ArgExprs.push_back(ParseIdentifierLoc());
558 } else {
559 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
561 Actions,
564
565 ExprResult ArgExpr(
567
568 if (ArgExpr.isInvalid()) {
569 SkipUntil(tok::r_paren, StopAtSemi);
570 return 0;
571 }
572 ArgExprs.push_back(ArgExpr.get());
573 }
574 // Eat the comma, move to the next argument
575 } while (TryConsumeToken(tok::comma));
576 } else {
577 // General case. Parse all available expressions.
578 bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
580 Actions, Uneval
583
584 ExprVector ParsedExprs;
586 attributeStringLiteralListArg(getTargetInfo().getTriple(), *AttrName);
587 if (ParseAttributeArgumentList(*AttrName, ParsedExprs, ArgProperties)) {
588 SkipUntil(tok::r_paren, StopAtSemi);
589 return 0;
590 }
591
592 // Pack expansion must currently be explicitly supported by an attribute.
593 for (size_t I = 0; I < ParsedExprs.size(); ++I) {
594 if (!isa<PackExpansionExpr>(ParsedExprs[I]))
595 continue;
596
597 if (!attributeAcceptsExprPack(*AttrName)) {
598 Diag(Tok.getLocation(),
599 diag::err_attribute_argument_parm_pack_not_supported)
600 << AttrName;
601 SkipUntil(tok::r_paren, StopAtSemi);
602 return 0;
603 }
604 }
605
606 ArgExprs.insert(ArgExprs.end(), ParsedExprs.begin(), ParsedExprs.end());
607 }
608 }
609
610 SourceLocation RParen = Tok.getLocation();
611 if (!ExpectAndConsume(tok::r_paren)) {
612 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
613
614 if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
615 Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
616 ScopeName, ScopeLoc, TheParsedType, Form);
617 } else {
618 Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
619 ArgExprs.data(), ArgExprs.size(), Form);
620 }
621 }
622
623 if (EndLoc)
624 *EndLoc = RParen;
625
626 return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
627}
628
629/// Parse the arguments to a parameterized GNU attribute or
630/// a C++11 attribute in "gnu" namespace.
631void Parser::ParseGNUAttributeArgs(
632 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
633 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
634 SourceLocation ScopeLoc, ParsedAttr::Form Form, Declarator *D) {
635
636 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
637
638 ParsedAttr::Kind AttrKind =
639 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
640
641 if (AttrKind == ParsedAttr::AT_Availability) {
642 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
643 ScopeLoc, Form);
644 return;
645 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
646 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
647 ScopeName, ScopeLoc, Form);
648 return;
649 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
650 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
651 ScopeName, ScopeLoc, Form);
652 return;
653 } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
654 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
655 ScopeLoc, Form);
656 return;
657 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
658 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
659 ScopeName, ScopeLoc, Form);
660 return;
661 } else if (attributeIsTypeArgAttr(*AttrName)) {
662 ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, ScopeName,
663 ScopeLoc, Form);
664 return;
665 } else if (AttrKind == ParsedAttr::AT_CountedBy) {
666 ParseBoundsAttribute(*AttrName, AttrNameLoc, Attrs, ScopeName, ScopeLoc,
667 Form);
668 return;
669 }
670
671 // These may refer to the function arguments, but need to be parsed early to
672 // participate in determining whether it's a redeclaration.
673 std::optional<ParseScope> PrototypeScope;
674 if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
675 D && D->isFunctionDeclarator()) {
677 PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
680 for (unsigned i = 0; i != FTI.NumParams; ++i) {
681 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
683 }
684 }
685
686 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
687 ScopeLoc, Form);
688}
689
690unsigned Parser::ParseClangAttributeArgs(
691 IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
692 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
693 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
694 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
695
696 ParsedAttr::Kind AttrKind =
697 ParsedAttr::getParsedKind(AttrName, ScopeName, Form.getSyntax());
698
699 switch (AttrKind) {
700 default:
701 return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
702 ScopeName, ScopeLoc, Form);
703 case ParsedAttr::AT_ExternalSourceSymbol:
704 ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
705 ScopeName, ScopeLoc, Form);
706 break;
707 case ParsedAttr::AT_Availability:
708 ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
709 ScopeLoc, Form);
710 break;
711 case ParsedAttr::AT_ObjCBridgeRelated:
712 ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
713 ScopeName, ScopeLoc, Form);
714 break;
715 case ParsedAttr::AT_SwiftNewType:
716 ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
717 ScopeLoc, Form);
718 break;
719 case ParsedAttr::AT_TypeTagForDatatype:
720 ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
721 ScopeName, ScopeLoc, Form);
722 break;
723 }
724 return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
725}
726
727bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
728 SourceLocation AttrNameLoc,
729 ParsedAttributes &Attrs) {
730 unsigned ExistingAttrs = Attrs.size();
731
732 // If the attribute isn't known, we will not attempt to parse any
733 // arguments.
736 // Eat the left paren, then skip to the ending right paren.
737 ConsumeParen();
738 SkipUntil(tok::r_paren);
739 return false;
740 }
741
742 SourceLocation OpenParenLoc = Tok.getLocation();
743
744 if (AttrName->getName() == "property") {
745 // The property declspec is more complex in that it can take one or two
746 // assignment expressions as a parameter, but the lhs of the assignment
747 // must be named get or put.
748
749 BalancedDelimiterTracker T(*this, tok::l_paren);
750 T.expectAndConsume(diag::err_expected_lparen_after,
751 AttrName->getNameStart(), tok::r_paren);
752
753 enum AccessorKind {
754 AK_Invalid = -1,
755 AK_Put = 0,
756 AK_Get = 1 // indices into AccessorNames
757 };
758 IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
759 bool HasInvalidAccessor = false;
760
761 // Parse the accessor specifications.
762 while (true) {
763 // Stop if this doesn't look like an accessor spec.
764 if (!Tok.is(tok::identifier)) {
765 // If the user wrote a completely empty list, use a special diagnostic.
766 if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
767 AccessorNames[AK_Put] == nullptr &&
768 AccessorNames[AK_Get] == nullptr) {
769 Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
770 break;
771 }
772
773 Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
774 break;
775 }
776
777 AccessorKind Kind;
778 SourceLocation KindLoc = Tok.getLocation();
779 StringRef KindStr = Tok.getIdentifierInfo()->getName();
780 if (KindStr == "get") {
781 Kind = AK_Get;
782 } else if (KindStr == "put") {
783 Kind = AK_Put;
784
785 // Recover from the common mistake of using 'set' instead of 'put'.
786 } else if (KindStr == "set") {
787 Diag(KindLoc, diag::err_ms_property_has_set_accessor)
788 << FixItHint::CreateReplacement(KindLoc, "put");
789 Kind = AK_Put;
790
791 // Handle the mistake of forgetting the accessor kind by skipping
792 // this accessor.
793 } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
794 Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
795 ConsumeToken();
796 HasInvalidAccessor = true;
797 goto next_property_accessor;
798
799 // Otherwise, complain about the unknown accessor kind.
800 } else {
801 Diag(KindLoc, diag::err_ms_property_unknown_accessor);
802 HasInvalidAccessor = true;
803 Kind = AK_Invalid;
804
805 // Try to keep parsing unless it doesn't look like an accessor spec.
806 if (!NextToken().is(tok::equal))
807 break;
808 }
809
810 // Consume the identifier.
811 ConsumeToken();
812
813 // Consume the '='.
814 if (!TryConsumeToken(tok::equal)) {
815 Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
816 << KindStr;
817 break;
818 }
819
820 // Expect the method name.
821 if (!Tok.is(tok::identifier)) {
822 Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
823 break;
824 }
825
826 if (Kind == AK_Invalid) {
827 // Just drop invalid accessors.
828 } else if (AccessorNames[Kind] != nullptr) {
829 // Complain about the repeated accessor, ignore it, and keep parsing.
830 Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
831 } else {
832 AccessorNames[Kind] = Tok.getIdentifierInfo();
833 }
834 ConsumeToken();
835
836 next_property_accessor:
837 // Keep processing accessors until we run out.
838 if (TryConsumeToken(tok::comma))
839 continue;
840
841 // If we run into the ')', stop without consuming it.
842 if (Tok.is(tok::r_paren))
843 break;
844
845 Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
846 break;
847 }
848
849 // Only add the property attribute if it was well-formed.
850 if (!HasInvalidAccessor)
851 Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
852 AccessorNames[AK_Get], AccessorNames[AK_Put],
853 ParsedAttr::Form::Declspec());
854 T.skipToEnd();
855 return !HasInvalidAccessor;
856 }
857
858 unsigned NumArgs =
859 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
860 SourceLocation(), ParsedAttr::Form::Declspec());
861
862 // If this attribute's args were parsed, and it was expected to have
863 // arguments but none were provided, emit a diagnostic.
864 if (ExistingAttrs < Attrs.size() && Attrs.back().getMaxArgs() && !NumArgs) {
865 Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
866 return false;
867 }
868 return true;
869}
870
871/// [MS] decl-specifier:
872/// __declspec ( extended-decl-modifier-seq )
873///
874/// [MS] extended-decl-modifier-seq:
875/// extended-decl-modifier[opt]
876/// extended-decl-modifier extended-decl-modifier-seq
877void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
878 assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
879 assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
880
881 SourceLocation StartLoc = Tok.getLocation();
882 SourceLocation EndLoc = StartLoc;
883
884 while (Tok.is(tok::kw___declspec)) {
885 ConsumeToken();
886 BalancedDelimiterTracker T(*this, tok::l_paren);
887 if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
888 tok::r_paren))
889 return;
890
891 // An empty declspec is perfectly legal and should not warn. Additionally,
892 // you can specify multiple attributes per declspec.
893 while (Tok.isNot(tok::r_paren)) {
894 // Attribute not present.
895 if (TryConsumeToken(tok::comma))
896 continue;
897
898 if (Tok.is(tok::code_completion)) {
899 cutOffParsing();
902 return;
903 }
904
905 // We expect either a well-known identifier or a generic string. Anything
906 // else is a malformed declspec.
907 bool IsString = Tok.getKind() == tok::string_literal;
908 if (!IsString && Tok.getKind() != tok::identifier &&
909 Tok.getKind() != tok::kw_restrict) {
910 Diag(Tok, diag::err_ms_declspec_type);
911 T.skipToEnd();
912 return;
913 }
914
915 IdentifierInfo *AttrName;
916 SourceLocation AttrNameLoc;
917 if (IsString) {
918 SmallString<8> StrBuffer;
919 bool Invalid = false;
920 StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
921 if (Invalid) {
922 T.skipToEnd();
923 return;
924 }
925 AttrName = PP.getIdentifierInfo(Str);
926 AttrNameLoc = ConsumeStringToken();
927 } else {
928 AttrName = Tok.getIdentifierInfo();
929 AttrNameLoc = ConsumeToken();
930 }
931
932 bool AttrHandled = false;
933
934 // Parse attribute arguments.
935 if (Tok.is(tok::l_paren))
936 AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
937 else if (AttrName->getName() == "property")
938 // The property attribute must have an argument list.
939 Diag(Tok.getLocation(), diag::err_expected_lparen_after)
940 << AttrName->getName();
941
942 if (!AttrHandled)
943 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
944 ParsedAttr::Form::Declspec());
945 }
946 T.consumeClose();
947 EndLoc = T.getCloseLocation();
948 }
949
950 Attrs.Range = SourceRange(StartLoc, EndLoc);
951}
952
953void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
954 // Treat these like attributes
955 while (true) {
956 auto Kind = Tok.getKind();
957 switch (Kind) {
958 case tok::kw___fastcall:
959 case tok::kw___stdcall:
960 case tok::kw___thiscall:
961 case tok::kw___regcall:
962 case tok::kw___cdecl:
963 case tok::kw___vectorcall:
964 case tok::kw___ptr64:
965 case tok::kw___w64:
966 case tok::kw___ptr32:
967 case tok::kw___sptr:
968 case tok::kw___uptr: {
969 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
970 SourceLocation AttrNameLoc = ConsumeToken();
971 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
972 Kind);
973 break;
974 }
975 default:
976 return;
977 }
978 }
979}
980
981void Parser::ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &attrs) {
982 assert(Tok.is(tok::kw___funcref));
983 SourceLocation StartLoc = Tok.getLocation();
984 if (!getTargetInfo().getTriple().isWasm()) {
985 ConsumeToken();
986 Diag(StartLoc, diag::err_wasm_funcref_not_wasm);
987 return;
988 }
989
990 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
991 SourceLocation AttrNameLoc = ConsumeToken();
992 attrs.addNew(AttrName, AttrNameLoc, /*ScopeName=*/nullptr,
993 /*ScopeLoc=*/SourceLocation{}, /*Args=*/nullptr, /*numArgs=*/0,
994 tok::kw___funcref);
995}
996
997void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
998 SourceLocation StartLoc = Tok.getLocation();
999 SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
1000
1001 if (EndLoc.isValid()) {
1002 SourceRange Range(StartLoc, EndLoc);
1003 Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
1004 }
1005}
1006
1007SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
1008 SourceLocation EndLoc;
1009
1010 while (true) {
1011 switch (Tok.getKind()) {
1012 case tok::kw_const:
1013 case tok::kw_volatile:
1014 case tok::kw___fastcall:
1015 case tok::kw___stdcall:
1016 case tok::kw___thiscall:
1017 case tok::kw___cdecl:
1018 case tok::kw___vectorcall:
1019 case tok::kw___ptr32:
1020 case tok::kw___ptr64:
1021 case tok::kw___w64:
1022 case tok::kw___unaligned:
1023 case tok::kw___sptr:
1024 case tok::kw___uptr:
1025 EndLoc = ConsumeToken();
1026 break;
1027 default:
1028 return EndLoc;
1029 }
1030 }
1031}
1032
1033void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
1034 // Treat these like attributes
1035 while (Tok.is(tok::kw___pascal)) {
1036 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1037 SourceLocation AttrNameLoc = ConsumeToken();
1038 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1039 tok::kw___pascal);
1040 }
1041}
1042
1043void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
1044 // Treat these like attributes
1045 while (Tok.is(tok::kw___kernel)) {
1046 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1047 SourceLocation AttrNameLoc = ConsumeToken();
1048 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1049 tok::kw___kernel);
1050 }
1051}
1052
1053void Parser::ParseCUDAFunctionAttributes(ParsedAttributes &attrs) {
1054 while (Tok.is(tok::kw___noinline__)) {
1055 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1056 SourceLocation AttrNameLoc = ConsumeToken();
1057 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1058 tok::kw___noinline__);
1059 }
1060}
1061
1062void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
1063 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1064 SourceLocation AttrNameLoc = Tok.getLocation();
1065 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1066 Tok.getKind());
1067}
1068
1069bool Parser::isHLSLQualifier(const Token &Tok) const {
1070 return Tok.is(tok::kw_groupshared);
1071}
1072
1073void Parser::ParseHLSLQualifiers(ParsedAttributes &Attrs) {
1074 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1075 auto Kind = Tok.getKind();
1076 SourceLocation AttrNameLoc = ConsumeToken();
1077 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, Kind);
1078}
1079
1080void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
1081 // Treat these like attributes, even though they're type specifiers.
1082 while (true) {
1083 auto Kind = Tok.getKind();
1084 switch (Kind) {
1085 case tok::kw__Nonnull:
1086 case tok::kw__Nullable:
1087 case tok::kw__Nullable_result:
1088 case tok::kw__Null_unspecified: {
1089 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1090 SourceLocation AttrNameLoc = ConsumeToken();
1091 if (!getLangOpts().ObjC)
1092 Diag(AttrNameLoc, diag::ext_nullability)
1093 << AttrName;
1094 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1095 Kind);
1096 break;
1097 }
1098 default:
1099 return;
1100 }
1101 }
1102}
1103
1104static bool VersionNumberSeparator(const char Separator) {
1105 return (Separator == '.' || Separator == '_');
1106}
1107
1108/// Parse a version number.
1109///
1110/// version:
1111/// simple-integer
1112/// simple-integer '.' simple-integer
1113/// simple-integer '_' simple-integer
1114/// simple-integer '.' simple-integer '.' simple-integer
1115/// simple-integer '_' simple-integer '_' simple-integer
1116VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
1117 Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
1118
1119 if (!Tok.is(tok::numeric_constant)) {
1120 Diag(Tok, diag::err_expected_version);
1121 SkipUntil(tok::comma, tok::r_paren,
1123 return VersionTuple();
1124 }
1125
1126 // Parse the major (and possibly minor and subminor) versions, which
1127 // are stored in the numeric constant. We utilize a quirk of the
1128 // lexer, which is that it handles something like 1.2.3 as a single
1129 // numeric constant, rather than two separate tokens.
1130 SmallString<512> Buffer;
1131 Buffer.resize(Tok.getLength()+1);
1132 const char *ThisTokBegin = &Buffer[0];
1133
1134 // Get the spelling of the token, which eliminates trigraphs, etc.
1135 bool Invalid = false;
1136 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1137 if (Invalid)
1138 return VersionTuple();
1139
1140 // Parse the major version.
1141 unsigned AfterMajor = 0;
1142 unsigned Major = 0;
1143 while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
1144 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
1145 ++AfterMajor;
1146 }
1147
1148 if (AfterMajor == 0) {
1149 Diag(Tok, diag::err_expected_version);
1150 SkipUntil(tok::comma, tok::r_paren,
1152 return VersionTuple();
1153 }
1154
1155 if (AfterMajor == ActualLength) {
1156 ConsumeToken();
1157
1158 // We only had a single version component.
1159 if (Major == 0) {
1160 Diag(Tok, diag::err_zero_version);
1161 return VersionTuple();
1162 }
1163
1164 return VersionTuple(Major);
1165 }
1166
1167 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
1168 if (!VersionNumberSeparator(AfterMajorSeparator)
1169 || (AfterMajor + 1 == ActualLength)) {
1170 Diag(Tok, diag::err_expected_version);
1171 SkipUntil(tok::comma, tok::r_paren,
1173 return VersionTuple();
1174 }
1175
1176 // Parse the minor version.
1177 unsigned AfterMinor = AfterMajor + 1;
1178 unsigned Minor = 0;
1179 while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
1180 Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
1181 ++AfterMinor;
1182 }
1183
1184 if (AfterMinor == ActualLength) {
1185 ConsumeToken();
1186
1187 // We had major.minor.
1188 if (Major == 0 && Minor == 0) {
1189 Diag(Tok, diag::err_zero_version);
1190 return VersionTuple();
1191 }
1192
1193 return VersionTuple(Major, Minor);
1194 }
1195
1196 const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
1197 // If what follows is not a '.' or '_', we have a problem.
1198 if (!VersionNumberSeparator(AfterMinorSeparator)) {
1199 Diag(Tok, diag::err_expected_version);
1200 SkipUntil(tok::comma, tok::r_paren,
1202 return VersionTuple();
1203 }
1204
1205 // Warn if separators, be it '.' or '_', do not match.
1206 if (AfterMajorSeparator != AfterMinorSeparator)
1207 Diag(Tok, diag::warn_expected_consistent_version_separator);
1208
1209 // Parse the subminor version.
1210 unsigned AfterSubminor = AfterMinor + 1;
1211 unsigned Subminor = 0;
1212 while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
1213 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
1214 ++AfterSubminor;
1215 }
1216
1217 if (AfterSubminor != ActualLength) {
1218 Diag(Tok, diag::err_expected_version);
1219 SkipUntil(tok::comma, tok::r_paren,
1221 return VersionTuple();
1222 }
1223 ConsumeToken();
1224 return VersionTuple(Major, Minor, Subminor);
1225}
1226
1227/// Parse the contents of the "availability" attribute.
1228///
1229/// availability-attribute:
1230/// 'availability' '(' platform ',' opt-strict version-arg-list,
1231/// opt-replacement, opt-message')'
1232///
1233/// platform:
1234/// identifier
1235///
1236/// opt-strict:
1237/// 'strict' ','
1238///
1239/// version-arg-list:
1240/// version-arg
1241/// version-arg ',' version-arg-list
1242///
1243/// version-arg:
1244/// 'introduced' '=' version
1245/// 'deprecated' '=' version
1246/// 'obsoleted' = version
1247/// 'unavailable'
1248/// opt-replacement:
1249/// 'replacement' '=' <string>
1250/// opt-message:
1251/// 'message' '=' <string>
1252void Parser::ParseAvailabilityAttribute(
1253 IdentifierInfo &Availability, SourceLocation AvailabilityLoc,
1254 ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName,
1255 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1256 enum { Introduced, Deprecated, Obsoleted, Unknown };
1257 AvailabilityChange Changes[Unknown];
1258 ExprResult MessageExpr, ReplacementExpr;
1259 IdentifierLoc *EnvironmentLoc = nullptr;
1260
1261 // Opening '('.
1262 BalancedDelimiterTracker T(*this, tok::l_paren);
1263 if (T.consumeOpen()) {
1264 Diag(Tok, diag::err_expected) << tok::l_paren;
1265 return;
1266 }
1267
1268 // Parse the platform name.
1269 if (Tok.isNot(tok::identifier)) {
1270 Diag(Tok, diag::err_availability_expected_platform);
1271 SkipUntil(tok::r_paren, StopAtSemi);
1272 return;
1273 }
1274 IdentifierLoc *Platform = ParseIdentifierLoc();
1275 if (const IdentifierInfo *const Ident = Platform->Ident) {
1276 // Disallow xrOS for availability attributes.
1277 if (Ident->getName().contains("xrOS") || Ident->getName().contains("xros"))
1278 Diag(Platform->Loc, diag::warn_availability_unknown_platform) << Ident;
1279 // Canonicalize platform name from "macosx" to "macos".
1280 else if (Ident->getName() == "macosx")
1281 Platform->Ident = PP.getIdentifierInfo("macos");
1282 // Canonicalize platform name from "macosx_app_extension" to
1283 // "macos_app_extension".
1284 else if (Ident->getName() == "macosx_app_extension")
1285 Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1286 else
1287 Platform->Ident = PP.getIdentifierInfo(
1288 AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1289 }
1290
1291 // Parse the ',' following the platform name.
1292 if (ExpectAndConsume(tok::comma)) {
1293 SkipUntil(tok::r_paren, StopAtSemi);
1294 return;
1295 }
1296
1297 // If we haven't grabbed the pointers for the identifiers
1298 // "introduced", "deprecated", and "obsoleted", do so now.
1299 if (!Ident_introduced) {
1300 Ident_introduced = PP.getIdentifierInfo("introduced");
1301 Ident_deprecated = PP.getIdentifierInfo("deprecated");
1302 Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1303 Ident_unavailable = PP.getIdentifierInfo("unavailable");
1304 Ident_message = PP.getIdentifierInfo("message");
1305 Ident_strict = PP.getIdentifierInfo("strict");
1306 Ident_replacement = PP.getIdentifierInfo("replacement");
1307 Ident_environment = PP.getIdentifierInfo("environment");
1308 }
1309
1310 // Parse the optional "strict", the optional "replacement" and the set of
1311 // introductions/deprecations/removals.
1312 SourceLocation UnavailableLoc, StrictLoc;
1313 do {
1314 if (Tok.isNot(tok::identifier)) {
1315 Diag(Tok, diag::err_availability_expected_change);
1316 SkipUntil(tok::r_paren, StopAtSemi);
1317 return;
1318 }
1319 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1320 SourceLocation KeywordLoc = ConsumeToken();
1321
1322 if (Keyword == Ident_strict) {
1323 if (StrictLoc.isValid()) {
1324 Diag(KeywordLoc, diag::err_availability_redundant)
1325 << Keyword << SourceRange(StrictLoc);
1326 }
1327 StrictLoc = KeywordLoc;
1328 continue;
1329 }
1330
1331 if (Keyword == Ident_unavailable) {
1332 if (UnavailableLoc.isValid()) {
1333 Diag(KeywordLoc, diag::err_availability_redundant)
1334 << Keyword << SourceRange(UnavailableLoc);
1335 }
1336 UnavailableLoc = KeywordLoc;
1337 continue;
1338 }
1339
1340 if (Keyword == Ident_deprecated && Platform->Ident &&
1341 Platform->Ident->isStr("swift")) {
1342 // For swift, we deprecate for all versions.
1343 if (Changes[Deprecated].KeywordLoc.isValid()) {
1344 Diag(KeywordLoc, diag::err_availability_redundant)
1345 << Keyword
1346 << SourceRange(Changes[Deprecated].KeywordLoc);
1347 }
1348
1349 Changes[Deprecated].KeywordLoc = KeywordLoc;
1350 // Use a fake version here.
1351 Changes[Deprecated].Version = VersionTuple(1);
1352 continue;
1353 }
1354
1355 if (Keyword == Ident_environment) {
1356 if (EnvironmentLoc != nullptr) {
1357 Diag(KeywordLoc, diag::err_availability_redundant)
1358 << Keyword << SourceRange(EnvironmentLoc->Loc);
1359 }
1360 }
1361
1362 if (Tok.isNot(tok::equal)) {
1363 Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1364 SkipUntil(tok::r_paren, StopAtSemi);
1365 return;
1366 }
1367 ConsumeToken();
1368 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1369 if (!isTokenStringLiteral()) {
1370 Diag(Tok, diag::err_expected_string_literal)
1371 << /*Source='availability attribute'*/2;
1372 SkipUntil(tok::r_paren, StopAtSemi);
1373 return;
1374 }
1375 if (Keyword == Ident_message) {
1377 break;
1378 } else {
1379 ReplacementExpr = ParseUnevaluatedStringLiteralExpression();
1380 continue;
1381 }
1382 }
1383 if (Keyword == Ident_environment) {
1384 if (Tok.isNot(tok::identifier)) {
1385 Diag(Tok, diag::err_availability_expected_environment);
1386 SkipUntil(tok::r_paren, StopAtSemi);
1387 return;
1388 }
1389 EnvironmentLoc = ParseIdentifierLoc();
1390 continue;
1391 }
1392
1393 // Special handling of 'NA' only when applied to introduced or
1394 // deprecated.
1395 if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1396 Tok.is(tok::identifier)) {
1398 if (NA->getName() == "NA") {
1399 ConsumeToken();
1400 if (Keyword == Ident_introduced)
1401 UnavailableLoc = KeywordLoc;
1402 continue;
1403 }
1404 }
1405
1406 SourceRange VersionRange;
1407 VersionTuple Version = ParseVersionTuple(VersionRange);
1408
1409 if (Version.empty()) {
1410 SkipUntil(tok::r_paren, StopAtSemi);
1411 return;
1412 }
1413
1414 unsigned Index;
1415 if (Keyword == Ident_introduced)
1416 Index = Introduced;
1417 else if (Keyword == Ident_deprecated)
1418 Index = Deprecated;
1419 else if (Keyword == Ident_obsoleted)
1420 Index = Obsoleted;
1421 else
1422 Index = Unknown;
1423
1424 if (Index < Unknown) {
1425 if (!Changes[Index].KeywordLoc.isInvalid()) {
1426 Diag(KeywordLoc, diag::err_availability_redundant)
1427 << Keyword
1428 << SourceRange(Changes[Index].KeywordLoc,
1429 Changes[Index].VersionRange.getEnd());
1430 }
1431
1432 Changes[Index].KeywordLoc = KeywordLoc;
1433 Changes[Index].Version = Version;
1434 Changes[Index].VersionRange = VersionRange;
1435 } else {
1436 Diag(KeywordLoc, diag::err_availability_unknown_change)
1437 << Keyword << VersionRange;
1438 }
1439
1440 } while (TryConsumeToken(tok::comma));
1441
1442 // Closing ')'.
1443 if (T.consumeClose())
1444 return;
1445
1446 if (endLoc)
1447 *endLoc = T.getCloseLocation();
1448
1449 // The 'unavailable' availability cannot be combined with any other
1450 // availability changes. Make sure that hasn't happened.
1451 if (UnavailableLoc.isValid()) {
1452 bool Complained = false;
1453 for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1454 if (Changes[Index].KeywordLoc.isValid()) {
1455 if (!Complained) {
1456 Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1457 << SourceRange(Changes[Index].KeywordLoc,
1458 Changes[Index].VersionRange.getEnd());
1459 Complained = true;
1460 }
1461
1462 // Clear out the availability.
1463 Changes[Index] = AvailabilityChange();
1464 }
1465 }
1466 }
1467
1468 // Record this attribute
1469 attrs.addNew(&Availability,
1470 SourceRange(AvailabilityLoc, T.getCloseLocation()), ScopeName,
1471 ScopeLoc, Platform, Changes[Introduced], Changes[Deprecated],
1472 Changes[Obsoleted], UnavailableLoc, MessageExpr.get(), Form,
1473 StrictLoc, ReplacementExpr.get(), EnvironmentLoc);
1474}
1475
1476/// Parse the contents of the "external_source_symbol" attribute.
1477///
1478/// external-source-symbol-attribute:
1479/// 'external_source_symbol' '(' keyword-arg-list ')'
1480///
1481/// keyword-arg-list:
1482/// keyword-arg
1483/// keyword-arg ',' keyword-arg-list
1484///
1485/// keyword-arg:
1486/// 'language' '=' <string>
1487/// 'defined_in' '=' <string>
1488/// 'USR' '=' <string>
1489/// 'generated_declaration'
1490void Parser::ParseExternalSourceSymbolAttribute(
1491 IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1492 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1493 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1494 // Opening '('.
1495 BalancedDelimiterTracker T(*this, tok::l_paren);
1496 if (T.expectAndConsume())
1497 return;
1498
1499 // Initialize the pointers for the keyword identifiers when required.
1500 if (!Ident_language) {
1501 Ident_language = PP.getIdentifierInfo("language");
1502 Ident_defined_in = PP.getIdentifierInfo("defined_in");
1503 Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1504 Ident_USR = PP.getIdentifierInfo("USR");
1505 }
1506
1508 bool HasLanguage = false;
1509 ExprResult DefinedInExpr;
1510 bool HasDefinedIn = false;
1511 IdentifierLoc *GeneratedDeclaration = nullptr;
1512 ExprResult USR;
1513 bool HasUSR = false;
1514
1515 // Parse the language/defined_in/generated_declaration keywords
1516 do {
1517 if (Tok.isNot(tok::identifier)) {
1518 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1519 SkipUntil(tok::r_paren, StopAtSemi);
1520 return;
1521 }
1522
1523 SourceLocation KeywordLoc = Tok.getLocation();
1524 IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1525 if (Keyword == Ident_generated_declaration) {
1526 if (GeneratedDeclaration) {
1527 Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1528 SkipUntil(tok::r_paren, StopAtSemi);
1529 return;
1530 }
1531 GeneratedDeclaration = ParseIdentifierLoc();
1532 continue;
1533 }
1534
1535 if (Keyword != Ident_language && Keyword != Ident_defined_in &&
1536 Keyword != Ident_USR) {
1537 Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1538 SkipUntil(tok::r_paren, StopAtSemi);
1539 return;
1540 }
1541
1542 ConsumeToken();
1543 if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1544 Keyword->getName())) {
1545 SkipUntil(tok::r_paren, StopAtSemi);
1546 return;
1547 }
1548
1549 bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn,
1550 HadUSR = HasUSR;
1551 if (Keyword == Ident_language)
1552 HasLanguage = true;
1553 else if (Keyword == Ident_USR)
1554 HasUSR = true;
1555 else
1556 HasDefinedIn = true;
1557
1558 if (!isTokenStringLiteral()) {
1559 Diag(Tok, diag::err_expected_string_literal)
1560 << /*Source='external_source_symbol attribute'*/ 3
1561 << /*language | source container | USR*/ (
1562 Keyword == Ident_language
1563 ? 0
1564 : (Keyword == Ident_defined_in ? 1 : 2));
1565 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1566 continue;
1567 }
1568 if (Keyword == Ident_language) {
1569 if (HadLanguage) {
1570 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1571 << Keyword;
1573 continue;
1574 }
1576 } else if (Keyword == Ident_USR) {
1577 if (HadUSR) {
1578 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1579 << Keyword;
1581 continue;
1582 }
1584 } else {
1585 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1586 if (HadDefinedIn) {
1587 Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1588 << Keyword;
1590 continue;
1591 }
1593 }
1594 } while (TryConsumeToken(tok::comma));
1595
1596 // Closing ')'.
1597 if (T.consumeClose())
1598 return;
1599 if (EndLoc)
1600 *EndLoc = T.getCloseLocation();
1601
1602 ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(), GeneratedDeclaration,
1603 USR.get()};
1604 Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1605 ScopeName, ScopeLoc, Args, std::size(Args), Form);
1606}
1607
1608/// Parse the contents of the "objc_bridge_related" attribute.
1609/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1610/// related_class:
1611/// Identifier
1612///
1613/// opt-class_method:
1614/// Identifier: | <empty>
1615///
1616/// opt-instance_method:
1617/// Identifier | <empty>
1618///
1619void Parser::ParseObjCBridgeRelatedAttribute(
1620 IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc,
1621 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1622 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1623 // Opening '('.
1624 BalancedDelimiterTracker T(*this, tok::l_paren);
1625 if (T.consumeOpen()) {
1626 Diag(Tok, diag::err_expected) << tok::l_paren;
1627 return;
1628 }
1629
1630 // Parse the related class name.
1631 if (Tok.isNot(tok::identifier)) {
1632 Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1633 SkipUntil(tok::r_paren, StopAtSemi);
1634 return;
1635 }
1636 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1637 if (ExpectAndConsume(tok::comma)) {
1638 SkipUntil(tok::r_paren, StopAtSemi);
1639 return;
1640 }
1641
1642 // Parse class method name. It's non-optional in the sense that a trailing
1643 // comma is required, but it can be the empty string, and then we record a
1644 // nullptr.
1645 IdentifierLoc *ClassMethod = nullptr;
1646 if (Tok.is(tok::identifier)) {
1647 ClassMethod = ParseIdentifierLoc();
1648 if (!TryConsumeToken(tok::colon)) {
1649 Diag(Tok, diag::err_objcbridge_related_selector_name);
1650 SkipUntil(tok::r_paren, StopAtSemi);
1651 return;
1652 }
1653 }
1654 if (!TryConsumeToken(tok::comma)) {
1655 if (Tok.is(tok::colon))
1656 Diag(Tok, diag::err_objcbridge_related_selector_name);
1657 else
1658 Diag(Tok, diag::err_expected) << tok::comma;
1659 SkipUntil(tok::r_paren, StopAtSemi);
1660 return;
1661 }
1662
1663 // Parse instance method name. Also non-optional but empty string is
1664 // permitted.
1665 IdentifierLoc *InstanceMethod = nullptr;
1666 if (Tok.is(tok::identifier))
1667 InstanceMethod = ParseIdentifierLoc();
1668 else if (Tok.isNot(tok::r_paren)) {
1669 Diag(Tok, diag::err_expected) << tok::r_paren;
1670 SkipUntil(tok::r_paren, StopAtSemi);
1671 return;
1672 }
1673
1674 // Closing ')'.
1675 if (T.consumeClose())
1676 return;
1677
1678 if (EndLoc)
1679 *EndLoc = T.getCloseLocation();
1680
1681 // Record this attribute
1682 Attrs.addNew(&ObjCBridgeRelated,
1683 SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1684 ScopeName, ScopeLoc, RelatedClass, ClassMethod, InstanceMethod,
1685 Form);
1686}
1687
1688void Parser::ParseSwiftNewTypeAttribute(
1689 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1690 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1691 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1692 BalancedDelimiterTracker T(*this, tok::l_paren);
1693
1694 // Opening '('
1695 if (T.consumeOpen()) {
1696 Diag(Tok, diag::err_expected) << tok::l_paren;
1697 return;
1698 }
1699
1700 if (Tok.is(tok::r_paren)) {
1701 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1702 T.consumeClose();
1703 return;
1704 }
1705 if (Tok.isNot(tok::kw_struct) && Tok.isNot(tok::kw_enum)) {
1706 Diag(Tok, diag::warn_attribute_type_not_supported)
1707 << &AttrName << Tok.getIdentifierInfo();
1708 if (!isTokenSpecial())
1709 ConsumeToken();
1710 T.consumeClose();
1711 return;
1712 }
1713
1714 auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1715 Tok.getIdentifierInfo());
1716 ConsumeToken();
1717
1718 // Closing ')'
1719 if (T.consumeClose())
1720 return;
1721 if (EndLoc)
1722 *EndLoc = T.getCloseLocation();
1723
1724 ArgsUnion Args[] = {SwiftType};
1725 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
1726 ScopeName, ScopeLoc, Args, std::size(Args), Form);
1727}
1728
1729void Parser::ParseTypeTagForDatatypeAttribute(
1730 IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1731 ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1732 SourceLocation ScopeLoc, ParsedAttr::Form Form) {
1733 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1734
1735 BalancedDelimiterTracker T(*this, tok::l_paren);
1736 T.consumeOpen();
1737
1738 if (Tok.isNot(tok::identifier)) {
1739 Diag(Tok, diag::err_expected) << tok::identifier;
1740 T.skipToEnd();
1741 return;
1742 }
1743 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1744
1745 if (ExpectAndConsume(tok::comma)) {
1746 T.skipToEnd();
1747 return;
1748 }
1749
1750 SourceRange MatchingCTypeRange;
1751 TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1752 if (MatchingCType.isInvalid()) {
1753 T.skipToEnd();
1754 return;
1755 }
1756
1757 bool LayoutCompatible = false;
1758 bool MustBeNull = false;
1759 while (TryConsumeToken(tok::comma)) {
1760 if (Tok.isNot(tok::identifier)) {
1761 Diag(Tok, diag::err_expected) << tok::identifier;
1762 T.skipToEnd();
1763 return;
1764 }
1765 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1766 if (Flag->isStr("layout_compatible"))
1767 LayoutCompatible = true;
1768 else if (Flag->isStr("must_be_null"))
1769 MustBeNull = true;
1770 else {
1771 Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1772 T.skipToEnd();
1773 return;
1774 }
1775 ConsumeToken(); // consume flag
1776 }
1777
1778 if (!T.consumeClose()) {
1779 Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1780 ArgumentKind, MatchingCType.get(),
1781 LayoutCompatible, MustBeNull, Form);
1782 }
1783
1784 if (EndLoc)
1785 *EndLoc = T.getCloseLocation();
1786}
1787
1788/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1789/// of a C++11 attribute-specifier in a location where an attribute is not
1790/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1791/// situation.
1792///
1793/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1794/// this doesn't appear to actually be an attribute-specifier, and the caller
1795/// should try to parse it.
1796bool Parser::DiagnoseProhibitedCXX11Attribute() {
1797 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1798
1799 switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1800 case CAK_NotAttributeSpecifier:
1801 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1802 return false;
1803
1804 case CAK_InvalidAttributeSpecifier:
1805 Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1806 return false;
1807
1808 case CAK_AttributeSpecifier:
1809 // Parse and discard the attributes.
1810 SourceLocation BeginLoc = ConsumeBracket();
1811 ConsumeBracket();
1812 SkipUntil(tok::r_square);
1813 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1814 SourceLocation EndLoc = ConsumeBracket();
1815 Diag(BeginLoc, diag::err_attributes_not_allowed)
1816 << SourceRange(BeginLoc, EndLoc);
1817 return true;
1818 }
1819 llvm_unreachable("All cases handled above.");
1820}
1821
1822/// We have found the opening square brackets of a C++11
1823/// attribute-specifier in a location where an attribute is not permitted, but
1824/// we know where the attributes ought to be written. Parse them anyway, and
1825/// provide a fixit moving them to the right place.
1826void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
1827 SourceLocation CorrectLocation) {
1828 assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1829 Tok.is(tok::kw_alignas) || Tok.isRegularKeywordAttribute());
1830
1831 // Consume the attributes.
1832 auto Keyword =
1833 Tok.isRegularKeywordAttribute() ? Tok.getIdentifierInfo() : nullptr;
1835 ParseCXX11Attributes(Attrs);
1836 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1837 // FIXME: use err_attributes_misplaced
1838 (Keyword ? Diag(Loc, diag::err_keyword_not_allowed) << Keyword
1839 : Diag(Loc, diag::err_attributes_not_allowed))
1840 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1841 << FixItHint::CreateRemoval(AttrRange);
1842}
1843
1844void Parser::DiagnoseProhibitedAttributes(
1845 const ParsedAttributesView &Attrs, const SourceLocation CorrectLocation) {
1846 auto *FirstAttr = Attrs.empty() ? nullptr : &Attrs.front();
1847 if (CorrectLocation.isValid()) {
1848 CharSourceRange AttrRange(Attrs.Range, true);
1849 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1850 ? Diag(CorrectLocation, diag::err_keyword_misplaced) << FirstAttr
1851 : Diag(CorrectLocation, diag::err_attributes_misplaced))
1852 << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1853 << FixItHint::CreateRemoval(AttrRange);
1854 } else {
1855 const SourceRange &Range = Attrs.Range;
1856 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1857 ? Diag(Range.getBegin(), diag::err_keyword_not_allowed) << FirstAttr
1858 : Diag(Range.getBegin(), diag::err_attributes_not_allowed))
1859 << Range;
1860 }
1861}
1862
1863void Parser::ProhibitCXX11Attributes(ParsedAttributes &Attrs,
1864 unsigned AttrDiagID,
1865 unsigned KeywordDiagID,
1866 bool DiagnoseEmptyAttrs,
1867 bool WarnOnUnknownAttrs) {
1868
1869 if (DiagnoseEmptyAttrs && Attrs.empty() && Attrs.Range.isValid()) {
1870 // An attribute list has been parsed, but it was empty.
1871 // This is the case for [[]].
1872 const auto &LangOpts = getLangOpts();
1873 auto &SM = PP.getSourceManager();
1874 Token FirstLSquare;
1875 Lexer::getRawToken(Attrs.Range.getBegin(), FirstLSquare, SM, LangOpts);
1876
1877 if (FirstLSquare.is(tok::l_square)) {
1878 std::optional<Token> SecondLSquare =
1879 Lexer::findNextToken(FirstLSquare.getLocation(), SM, LangOpts);
1880
1881 if (SecondLSquare && SecondLSquare->is(tok::l_square)) {
1882 // The attribute range starts with [[, but is empty. So this must
1883 // be [[]], which we are supposed to diagnose because
1884 // DiagnoseEmptyAttrs is true.
1885 Diag(Attrs.Range.getBegin(), AttrDiagID) << Attrs.Range;
1886 return;
1887 }
1888 }
1889 }
1890
1891 for (const ParsedAttr &AL : Attrs) {
1892 if (AL.isRegularKeywordAttribute()) {
1893 Diag(AL.getLoc(), KeywordDiagID) << AL;
1894 AL.setInvalid();
1895 continue;
1896 }
1897 if (!AL.isStandardAttributeSyntax())
1898 continue;
1899 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
1900 if (WarnOnUnknownAttrs)
1901 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1902 << AL << AL.getRange();
1903 } else {
1904 Diag(AL.getLoc(), AttrDiagID) << AL;
1905 AL.setInvalid();
1906 }
1907 }
1908}
1909
1910void Parser::DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs) {
1911 for (const ParsedAttr &PA : Attrs) {
1912 if (PA.isStandardAttributeSyntax() || PA.isRegularKeywordAttribute())
1913 Diag(PA.getLoc(), diag::ext_cxx11_attr_placement)
1914 << PA << PA.isRegularKeywordAttribute() << PA.getRange();
1915 }
1916}
1917
1918// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1919// applies to var, not the type Foo.
1920// As an exception to the rule, __declspec(align(...)) before the
1921// class-key affects the type instead of the variable.
1922// Also, Microsoft-style [attributes] seem to affect the type instead of the
1923// variable.
1924// This function moves attributes that should apply to the type off DS to Attrs.
1925void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs,
1926 DeclSpec &DS,
1927 Sema::TagUseKind TUK) {
1928 if (TUK == Sema::TUK_Reference)
1929 return;
1930
1932
1933 for (ParsedAttr &AL : DS.getAttributes()) {
1934 if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1935 AL.isDeclspecAttribute()) ||
1936 AL.isMicrosoftAttribute())
1937 ToBeMoved.push_back(&AL);
1938 }
1939
1940 for (ParsedAttr *AL : ToBeMoved) {
1941 DS.getAttributes().remove(AL);
1942 Attrs.addAtEnd(AL);
1943 }
1944}
1945
1946/// ParseDeclaration - Parse a full 'declaration', which consists of
1947/// declaration-specifiers, some number of declarators, and a semicolon.
1948/// 'Context' should be a DeclaratorContext value. This returns the
1949/// location of the semicolon in DeclEnd.
1950///
1951/// declaration: [C99 6.7]
1952/// block-declaration ->
1953/// simple-declaration
1954/// others [FIXME]
1955/// [C++] template-declaration
1956/// [C++] namespace-definition
1957/// [C++] using-directive
1958/// [C++] using-declaration
1959/// [C++11/C11] static_assert-declaration
1960/// others... [FIXME]
1961///
1962Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
1963 SourceLocation &DeclEnd,
1964 ParsedAttributes &DeclAttrs,
1965 ParsedAttributes &DeclSpecAttrs,
1966 SourceLocation *DeclSpecStart) {
1967 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1968 // Must temporarily exit the objective-c container scope for
1969 // parsing c none objective-c decls.
1970 ObjCDeclContextSwitch ObjCDC(*this);
1971
1972 Decl *SingleDecl = nullptr;
1973 switch (Tok.getKind()) {
1974 case tok::kw_template:
1975 case tok::kw_export:
1976 ProhibitAttributes(DeclAttrs);
1977 ProhibitAttributes(DeclSpecAttrs);
1978 return ParseDeclarationStartingWithTemplate(Context, DeclEnd, DeclAttrs);
1979 case tok::kw_inline:
1980 // Could be the start of an inline namespace. Allowed as an ext in C++03.
1981 if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1982 ProhibitAttributes(DeclAttrs);
1983 ProhibitAttributes(DeclSpecAttrs);
1984 SourceLocation InlineLoc = ConsumeToken();
1985 return ParseNamespace(Context, DeclEnd, InlineLoc);
1986 }
1987 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1988 true, nullptr, DeclSpecStart);
1989
1990 case tok::kw_cbuffer:
1991 case tok::kw_tbuffer:
1992 SingleDecl = ParseHLSLBuffer(DeclEnd);
1993 break;
1994 case tok::kw_namespace:
1995 ProhibitAttributes(DeclAttrs);
1996 ProhibitAttributes(DeclSpecAttrs);
1997 return ParseNamespace(Context, DeclEnd);
1998 case tok::kw_using: {
1999 ParsedAttributes Attrs(AttrFactory);
2000 takeAndConcatenateAttrs(DeclAttrs, DeclSpecAttrs, Attrs);
2001 return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
2002 DeclEnd, Attrs);
2003 }
2004 case tok::kw_static_assert:
2005 case tok::kw__Static_assert:
2006 ProhibitAttributes(DeclAttrs);
2007 ProhibitAttributes(DeclSpecAttrs);
2008 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
2009 break;
2010 default:
2011 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
2012 true, nullptr, DeclSpecStart);
2013 }
2014
2015 // This routine returns a DeclGroup, if the thing we parsed only contains a
2016 // single decl, convert it now.
2017 return Actions.ConvertDeclToDeclGroup(SingleDecl);
2018}
2019
2020/// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
2021/// declaration-specifiers init-declarator-list[opt] ';'
2022/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
2023/// init-declarator-list ';'
2024///[C90/C++]init-declarator-list ';' [TODO]
2025/// [OMP] threadprivate-directive
2026/// [OMP] allocate-directive [TODO]
2027///
2028/// for-range-declaration: [C++11 6.5p1: stmt.ranged]
2029/// attribute-specifier-seq[opt] type-specifier-seq declarator
2030///
2031/// If RequireSemi is false, this does not check for a ';' at the end of the
2032/// declaration. If it is true, it checks for and eats it.
2033///
2034/// If FRI is non-null, we might be parsing a for-range-declaration instead
2035/// of a simple-declaration. If we find that we are, we also parse the
2036/// for-range-initializer, and place it here.
2037///
2038/// DeclSpecStart is used when decl-specifiers are parsed before parsing
2039/// the Declaration. The SourceLocation for this Decl is set to
2040/// DeclSpecStart if DeclSpecStart is non-null.
2041Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
2042 DeclaratorContext Context, SourceLocation &DeclEnd,
2043 ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
2044 bool RequireSemi, ForRangeInit *FRI, SourceLocation *DeclSpecStart) {
2045 // Need to retain these for diagnostics before we add them to the DeclSepc.
2046 ParsedAttributesView OriginalDeclSpecAttrs;
2047 OriginalDeclSpecAttrs.addAll(DeclSpecAttrs.begin(), DeclSpecAttrs.end());
2048 OriginalDeclSpecAttrs.Range = DeclSpecAttrs.Range;
2049
2050 // Parse the common declaration-specifiers piece.
2051 ParsingDeclSpec DS(*this);
2052 DS.takeAttributesFrom(DeclSpecAttrs);
2053
2054 ParsedTemplateInfo TemplateInfo;
2055 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
2056 ParseDeclarationSpecifiers(DS, TemplateInfo, AS_none, DSContext);
2057
2058 // If we had a free-standing type definition with a missing semicolon, we
2059 // may get this far before the problem becomes obvious.
2060 if (DS.hasTagDefinition() &&
2061 DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
2062 return nullptr;
2063
2064 // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
2065 // declaration-specifiers init-declarator-list[opt] ';'
2066 if (Tok.is(tok::semi)) {
2067 ProhibitAttributes(DeclAttrs);
2068 DeclEnd = Tok.getLocation();
2069 if (RequireSemi) ConsumeToken();
2070 RecordDecl *AnonRecord = nullptr;
2071 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2072 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
2073 Actions.ActOnDefinedDeclarationSpecifier(TheDecl);
2074 DS.complete(TheDecl);
2075 if (AnonRecord) {
2076 Decl* decls[] = {AnonRecord, TheDecl};
2077 return Actions.BuildDeclaratorGroup(decls);
2078 }
2079 return Actions.ConvertDeclToDeclGroup(TheDecl);
2080 }
2081
2082 if (DS.hasTagDefinition())
2084
2085 if (DeclSpecStart)
2086 DS.SetRangeStart(*DeclSpecStart);
2087
2088 return ParseDeclGroup(DS, Context, DeclAttrs, TemplateInfo, &DeclEnd, FRI);
2089}
2090
2091/// Returns true if this might be the start of a declarator, or a common typo
2092/// for a declarator.
2093bool Parser::MightBeDeclarator(DeclaratorContext Context) {
2094 switch (Tok.getKind()) {
2095 case tok::annot_cxxscope:
2096 case tok::annot_template_id:
2097 case tok::caret:
2098 case tok::code_completion:
2099 case tok::coloncolon:
2100 case tok::ellipsis:
2101 case tok::kw___attribute:
2102 case tok::kw_operator:
2103 case tok::l_paren:
2104 case tok::star:
2105 return true;
2106
2107 case tok::amp:
2108 case tok::ampamp:
2109 return getLangOpts().CPlusPlus;
2110
2111 case tok::l_square: // Might be an attribute on an unnamed bit-field.
2112 return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
2113 NextToken().is(tok::l_square);
2114
2115 case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
2116 return Context == DeclaratorContext::Member || getLangOpts().CPlusPlus;
2117
2118 case tok::identifier:
2119 switch (NextToken().getKind()) {
2120 case tok::code_completion:
2121 case tok::coloncolon:
2122 case tok::comma:
2123 case tok::equal:
2124 case tok::equalequal: // Might be a typo for '='.
2125 case tok::kw_alignas:
2126 case tok::kw_asm:
2127 case tok::kw___attribute:
2128 case tok::l_brace:
2129 case tok::l_paren:
2130 case tok::l_square:
2131 case tok::less:
2132 case tok::r_brace:
2133 case tok::r_paren:
2134 case tok::r_square:
2135 case tok::semi:
2136 return true;
2137
2138 case tok::colon:
2139 // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
2140 // and in block scope it's probably a label. Inside a class definition,
2141 // this is a bit-field.
2142 return Context == DeclaratorContext::Member ||
2143 (getLangOpts().CPlusPlus && Context == DeclaratorContext::File);
2144
2145 case tok::identifier: // Possible virt-specifier.
2146 return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
2147
2148 default:
2149 return Tok.isRegularKeywordAttribute();
2150 }
2151
2152 default:
2153 return Tok.isRegularKeywordAttribute();
2154 }
2155}
2156
2157/// Skip until we reach something which seems like a sensible place to pick
2158/// up parsing after a malformed declaration. This will sometimes stop sooner
2159/// than SkipUntil(tok::r_brace) would, but will never stop later.
2161 while (true) {
2162 switch (Tok.getKind()) {
2163 case tok::l_brace:
2164 // Skip until matching }, then stop. We've probably skipped over
2165 // a malformed class or function definition or similar.
2166 ConsumeBrace();
2167 SkipUntil(tok::r_brace);
2168 if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
2169 // This declaration isn't over yet. Keep skipping.
2170 continue;
2171 }
2172 TryConsumeToken(tok::semi);
2173 return;
2174
2175 case tok::l_square:
2176 ConsumeBracket();
2177 SkipUntil(tok::r_square);
2178 continue;
2179
2180 case tok::l_paren:
2181 ConsumeParen();
2182 SkipUntil(tok::r_paren);
2183 continue;
2184
2185 case tok::r_brace:
2186 return;
2187
2188 case tok::semi:
2189 ConsumeToken();
2190 return;
2191
2192 case tok::kw_inline:
2193 // 'inline namespace' at the start of a line is almost certainly
2194 // a good place to pick back up parsing, except in an Objective-C
2195 // @interface context.
2196 if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
2197 (!ParsingInObjCContainer || CurParsedObjCImpl))
2198 return;
2199 break;
2200
2201 case tok::kw_namespace:
2202 // 'namespace' at the start of a line is almost certainly a good
2203 // place to pick back up parsing, except in an Objective-C
2204 // @interface context.
2205 if (Tok.isAtStartOfLine() &&
2206 (!ParsingInObjCContainer || CurParsedObjCImpl))
2207 return;
2208 break;
2209
2210 case tok::at:
2211 // @end is very much like } in Objective-C contexts.
2212 if (NextToken().isObjCAtKeyword(tok::objc_end) &&
2213 ParsingInObjCContainer)
2214 return;
2215 break;
2216
2217 case tok::minus:
2218 case tok::plus:
2219 // - and + probably start new method declarations in Objective-C contexts.
2220 if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
2221 return;
2222 break;
2223
2224 case tok::eof:
2225 case tok::annot_module_begin:
2226 case tok::annot_module_end:
2227 case tok::annot_module_include:
2228 case tok::annot_repl_input_end:
2229 return;
2230
2231 default:
2232 break;
2233 }
2234
2236 }
2237}
2238
2239/// ParseDeclGroup - Having concluded that this is either a function
2240/// definition or a group of object declarations, actually parse the
2241/// result.
2242Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2243 DeclaratorContext Context,
2244 ParsedAttributes &Attrs,
2245 ParsedTemplateInfo &TemplateInfo,
2246 SourceLocation *DeclEnd,
2247 ForRangeInit *FRI) {
2248 // Parse the first declarator.
2249 // Consume all of the attributes from `Attrs` by moving them to our own local
2250 // list. This ensures that we will not attempt to interpret them as statement
2251 // attributes higher up the callchain.
2252 ParsedAttributes LocalAttrs(AttrFactory);
2253 LocalAttrs.takeAllFrom(Attrs);
2254 ParsingDeclarator D(*this, DS, LocalAttrs, Context);
2255 if (TemplateInfo.TemplateParams)
2256 D.setTemplateParameterLists(*TemplateInfo.TemplateParams);
2257
2258 bool IsTemplateSpecOrInst =
2259 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
2260 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
2261 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
2262
2263 ParseDeclarator(D);
2264
2265 if (IsTemplateSpecOrInst)
2266 SAC.done();
2267
2268 // Bail out if the first declarator didn't seem well-formed.
2269 if (!D.hasName() && !D.mayOmitIdentifier()) {
2271 return nullptr;
2272 }
2273
2274 if (getLangOpts().HLSL)
2275 MaybeParseHLSLAnnotations(D);
2276
2277 if (Tok.is(tok::kw_requires))
2278 ParseTrailingRequiresClause(D);
2279
2280 // Save late-parsed attributes for now; they need to be parsed in the
2281 // appropriate function scope after the function Decl has been constructed.
2282 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2283 LateParsedAttrList LateParsedAttrs(true);
2284 if (D.isFunctionDeclarator()) {
2285 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2286
2287 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2288 // attribute. If we find the keyword here, tell the user to put it
2289 // at the start instead.
2290 if (Tok.is(tok::kw__Noreturn)) {
2292 const char *PrevSpec;
2293 unsigned DiagID;
2294
2295 // We can offer a fixit if it's valid to mark this function as _Noreturn
2296 // and we don't have any other declarators in this declaration.
2297 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2298 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2299 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2300
2301 Diag(Loc, diag::err_c11_noreturn_misplaced)
2302 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2303 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2304 : FixItHint());
2305 }
2306
2307 // Check to see if we have a function *definition* which must have a body.
2308 if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
2309 cutOffParsing();
2311 return nullptr;
2312 }
2313 // We're at the point where the parsing of function declarator is finished.
2314 //
2315 // A common error is that users accidently add a virtual specifier
2316 // (e.g. override) in an out-line method definition.
2317 // We attempt to recover by stripping all these specifiers coming after
2318 // the declarator.
2319 while (auto Specifier = isCXX11VirtSpecifier()) {
2320 Diag(Tok, diag::err_virt_specifier_outside_class)
2323 ConsumeToken();
2324 }
2325 // Look at the next token to make sure that this isn't a function
2326 // declaration. We have to check this because __attribute__ might be the
2327 // start of a function definition in GCC-extended K&R C.
2328 if (!isDeclarationAfterDeclarator()) {
2329
2330 // Function definitions are only allowed at file scope and in C++ classes.
2331 // The C++ inline method definition case is handled elsewhere, so we only
2332 // need to handle the file scope definition case.
2333 if (Context == DeclaratorContext::File) {
2334 if (isStartOfFunctionDefinition(D)) {
2335 // C++23 [dcl.typedef] p1:
2336 // The typedef specifier shall not be [...], and it shall not be
2337 // used in the decl-specifier-seq of a parameter-declaration nor in
2338 // the decl-specifier-seq of a function-definition.
2340 // If the user intended to write 'typename', we should have already
2341 // suggested adding it elsewhere. In any case, recover by ignoring
2342 // 'typedef' and suggest removing it.
2344 diag::err_function_declared_typedef)
2347 }
2348 Decl *TheDecl = nullptr;
2349
2350 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
2352 // If the declarator-id is not a template-id, issue a diagnostic
2353 // and recover by ignoring the 'template' keyword.
2354 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
2355 TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
2356 &LateParsedAttrs);
2357 } else {
2358 SourceLocation LAngleLoc =
2359 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2361 diag::err_explicit_instantiation_with_definition)
2362 << SourceRange(TemplateInfo.TemplateLoc)
2363 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2364
2365 // Recover as if it were an explicit specialization.
2366 TemplateParameterLists FakedParamLists;
2367 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2368 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc,
2369 std::nullopt, LAngleLoc, nullptr));
2370
2371 TheDecl = ParseFunctionDefinition(
2372 D,
2373 ParsedTemplateInfo(&FakedParamLists,
2374 /*isSpecialization=*/true,
2375 /*lastParameterListWasEmpty=*/true),
2376 &LateParsedAttrs);
2377 }
2378 } else {
2379 TheDecl =
2380 ParseFunctionDefinition(D, TemplateInfo, &LateParsedAttrs);
2381 }
2382
2383 return Actions.ConvertDeclToDeclGroup(TheDecl);
2384 }
2385
2386 if (isDeclarationSpecifier(ImplicitTypenameContext::No) ||
2387 Tok.is(tok::kw_namespace)) {
2388 // If there is an invalid declaration specifier or a namespace
2389 // definition right after the function prototype, then we must be in a
2390 // missing semicolon case where this isn't actually a body. Just fall
2391 // through into the code that handles it as a prototype, and let the
2392 // top-level code handle the erroneous declspec where it would
2393 // otherwise expect a comma or semicolon. Note that
2394 // isDeclarationSpecifier already covers 'inline namespace', since
2395 // 'inline' can be a declaration specifier.
2396 } else {
2397 Diag(Tok, diag::err_expected_fn_body);
2398 SkipUntil(tok::semi);
2399 return nullptr;
2400 }
2401 } else {
2402 if (Tok.is(tok::l_brace)) {
2403 Diag(Tok, diag::err_function_definition_not_allowed);
2405 return nullptr;
2406 }
2407 }
2408 }
2409 }
2410
2411 if (ParseAsmAttributesAfterDeclarator(D))
2412 return nullptr;
2413
2414 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2415 // must parse and analyze the for-range-initializer before the declaration is
2416 // analyzed.
2417 //
2418 // Handle the Objective-C for-in loop variable similarly, although we
2419 // don't need to parse the container in advance.
2420 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2421 bool IsForRangeLoop = false;
2422 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2423 IsForRangeLoop = true;
2424 EnterExpressionEvaluationContext ForRangeInitContext(
2426 /*LambdaContextDecl=*/nullptr,
2429
2430 // P2718R0 - Lifetime extension in range-based for loops.
2431 if (getLangOpts().CPlusPlus23) {
2432 auto &LastRecord = Actions.ExprEvalContexts.back();
2433 LastRecord.InLifetimeExtendingContext = true;
2434 }
2435
2436 if (getLangOpts().OpenMP)
2437 Actions.OpenMP().startOpenMPCXXRangeFor();
2438 if (Tok.is(tok::l_brace))
2439 FRI->RangeExpr = ParseBraceInitializer();
2440 else
2441 FRI->RangeExpr = ParseExpression();
2442
2443 // Before c++23, ForRangeLifetimeExtendTemps should be empty.
2444 assert(
2446 Actions.ExprEvalContexts.back().ForRangeLifetimeExtendTemps.empty());
2447
2448 // Move the collected materialized temporaries into ForRangeInit before
2449 // ForRangeInitContext exit.
2450 FRI->LifetimeExtendTemps = std::move(
2451 Actions.ExprEvalContexts.back().ForRangeLifetimeExtendTemps);
2452 }
2453
2454 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2455 if (IsForRangeLoop) {
2456 Actions.ActOnCXXForRangeDecl(ThisDecl);
2457 } else {
2458 // Obj-C for loop
2459 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2460 VD->setObjCForDecl(true);
2461 }
2462 Actions.FinalizeDeclaration(ThisDecl);
2463 D.complete(ThisDecl);
2464 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2465 }
2466
2467 SmallVector<Decl *, 8> DeclsInGroup;
2468 Decl *FirstDecl =
2469 ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo, FRI);
2470 if (LateParsedAttrs.size() > 0)
2471 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2472 D.complete(FirstDecl);
2473 if (FirstDecl)
2474 DeclsInGroup.push_back(FirstDecl);
2475
2476 bool ExpectSemi = Context != DeclaratorContext::ForInit;
2477
2478 // If we don't have a comma, it is either the end of the list (a ';') or an
2479 // error, bail out.
2480 SourceLocation CommaLoc;
2481 while (TryConsumeToken(tok::comma, CommaLoc)) {
2482 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2483 // This comma was followed by a line-break and something which can't be
2484 // the start of a declarator. The comma was probably a typo for a
2485 // semicolon.
2486 Diag(CommaLoc, diag::err_expected_semi_declaration)
2487 << FixItHint::CreateReplacement(CommaLoc, ";");
2488 ExpectSemi = false;
2489 break;
2490 }
2491
2492 // C++23 [temp.pre]p5:
2493 // In a template-declaration, explicit specialization, or explicit
2494 // instantiation the init-declarator-list in the declaration shall
2495 // contain at most one declarator.
2496 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
2497 D.isFirstDeclarator()) {
2498 Diag(CommaLoc, diag::err_multiple_template_declarators)
2499 << TemplateInfo.Kind;
2500 }
2501
2502 // Parse the next declarator.
2503 D.clear();
2504 D.setCommaLoc(CommaLoc);
2505
2506 // Accept attributes in an init-declarator. In the first declarator in a
2507 // declaration, these would be part of the declspec. In subsequent
2508 // declarators, they become part of the declarator itself, so that they
2509 // don't apply to declarators after *this* one. Examples:
2510 // short __attribute__((common)) var; -> declspec
2511 // short var __attribute__((common)); -> declarator
2512 // short x, __attribute__((common)) var; -> declarator
2513 MaybeParseGNUAttributes(D);
2514
2515 // MSVC parses but ignores qualifiers after the comma as an extension.
2516 if (getLangOpts().MicrosoftExt)
2517 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2518
2519 ParseDeclarator(D);
2520
2521 if (getLangOpts().HLSL)
2522 MaybeParseHLSLAnnotations(D);
2523
2524 if (!D.isInvalidType()) {
2525 // C++2a [dcl.decl]p1
2526 // init-declarator:
2527 // declarator initializer[opt]
2528 // declarator requires-clause
2529 if (Tok.is(tok::kw_requires))
2530 ParseTrailingRequiresClause(D);
2531 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D, TemplateInfo);
2532 D.complete(ThisDecl);
2533 if (ThisDecl)
2534 DeclsInGroup.push_back(ThisDecl);
2535 }
2536 }
2537
2538 if (DeclEnd)
2539 *DeclEnd = Tok.getLocation();
2540
2541 if (ExpectSemi && ExpectAndConsumeSemi(
2542 Context == DeclaratorContext::File
2543 ? diag::err_invalid_token_after_toplevel_declarator
2544 : diag::err_expected_semi_declaration)) {
2545 // Okay, there was no semicolon and one was expected. If we see a
2546 // declaration specifier, just assume it was missing and continue parsing.
2547 // Otherwise things are very confused and we skip to recover.
2548 if (!isDeclarationSpecifier(ImplicitTypenameContext::No))
2550 }
2551
2552 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2553}
2554
2555/// Parse an optional simple-asm-expr and attributes, and attach them to a
2556/// declarator. Returns true on an error.
2557bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2558 // If a simple-asm-expr is present, parse it.
2559 if (Tok.is(tok::kw_asm)) {
2561 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2562 if (AsmLabel.isInvalid()) {
2563 SkipUntil(tok::semi, StopBeforeMatch);
2564 return true;
2565 }
2566
2567 D.setAsmLabel(AsmLabel.get());
2568 D.SetRangeEnd(Loc);
2569 }
2570
2571 MaybeParseGNUAttributes(D);
2572 return false;
2573}
2574
2575/// Parse 'declaration' after parsing 'declaration-specifiers
2576/// declarator'. This method parses the remainder of the declaration
2577/// (including any attributes or initializer, among other things) and
2578/// finalizes the declaration.
2579///
2580/// init-declarator: [C99 6.7]
2581/// declarator
2582/// declarator '=' initializer
2583/// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2584/// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2585/// [C++] declarator initializer[opt]
2586///
2587/// [C++] initializer:
2588/// [C++] '=' initializer-clause
2589/// [C++] '(' expression-list ')'
2590/// [C++0x] '=' 'default' [TODO]
2591/// [C++0x] '=' 'delete'
2592/// [C++0x] braced-init-list
2593///
2594/// According to the standard grammar, =default and =delete are function
2595/// definitions, but that definitely doesn't fit with the parser here.
2596///
2597Decl *Parser::ParseDeclarationAfterDeclarator(
2598 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2599 if (ParseAsmAttributesAfterDeclarator(D))
2600 return nullptr;
2601
2602 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2603}
2604
2605Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2606 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2607 // RAII type used to track whether we're inside an initializer.
2608 struct InitializerScopeRAII {
2609 Parser &P;
2610 Declarator &D;
2611 Decl *ThisDecl;
2612 bool Entered;
2613
2614 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2615 : P(P), D(D), ThisDecl(ThisDecl), Entered(false) {
2616 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2617 Scope *S = nullptr;
2618 if (D.getCXXScopeSpec().isSet()) {
2619 P.EnterScope(0);
2620 S = P.getCurScope();
2621 }
2622 if (ThisDecl && !ThisDecl->isInvalidDecl()) {
2623 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2624 Entered = true;
2625 }
2626 }
2627 }
2628 ~InitializerScopeRAII() {
2629 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2630 Scope *S = nullptr;
2631 if (D.getCXXScopeSpec().isSet())
2632 S = P.getCurScope();
2633
2634 if (Entered)
2635 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2636 if (S)
2637 P.ExitScope();
2638 }
2639 ThisDecl = nullptr;
2640 }
2641 };
2642
2643 enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
2644 InitKind TheInitKind;
2645 // If a '==' or '+=' is found, suggest a fixit to '='.
2646 if (isTokenEqualOrEqualTypo())
2647 TheInitKind = InitKind::Equal;
2648 else if (Tok.is(tok::l_paren))
2649 TheInitKind = InitKind::CXXDirect;
2650 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2651 (!CurParsedObjCImpl || !D.isFunctionDeclarator()))
2652 TheInitKind = InitKind::CXXBraced;
2653 else
2654 TheInitKind = InitKind::Uninitialized;
2655 if (TheInitKind != InitKind::Uninitialized)
2657
2658 // Inform Sema that we just parsed this declarator.
2659 Decl *ThisDecl = nullptr;
2660 Decl *OuterDecl = nullptr;
2661 switch (TemplateInfo.Kind) {
2662 case ParsedTemplateInfo::NonTemplate:
2663 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2664 break;
2665
2666 case ParsedTemplateInfo::Template:
2667 case ParsedTemplateInfo::ExplicitSpecialization: {
2668 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2669 *TemplateInfo.TemplateParams,
2670 D);
2671 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2672 // Re-direct this decl to refer to the templated decl so that we can
2673 // initialize it.
2674 ThisDecl = VT->getTemplatedDecl();
2675 OuterDecl = VT;
2676 }
2677 break;
2678 }
2679 case ParsedTemplateInfo::ExplicitInstantiation: {
2680 if (Tok.is(tok::semi)) {
2681 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2682 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2683 if (ThisRes.isInvalid()) {
2684 SkipUntil(tok::semi, StopBeforeMatch);
2685 return nullptr;
2686 }
2687 ThisDecl = ThisRes.get();
2688 } else {
2689 // FIXME: This check should be for a variable template instantiation only.
2690
2691 // Check that this is a valid instantiation
2693 // If the declarator-id is not a template-id, issue a diagnostic and
2694 // recover by ignoring the 'template' keyword.
2695 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2696 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2697 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2698 } else {
2699 SourceLocation LAngleLoc =
2700 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2702 diag::err_explicit_instantiation_with_definition)
2703 << SourceRange(TemplateInfo.TemplateLoc)
2704 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2705
2706 // Recover as if it were an explicit specialization.
2707 TemplateParameterLists FakedParamLists;
2708 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2709 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc,
2710 std::nullopt, LAngleLoc, nullptr));
2711
2712 ThisDecl =
2713 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2714 }
2715 }
2716 break;
2717 }
2718 }
2719
2722 switch (TheInitKind) {
2723 // Parse declarator '=' initializer.
2724 case InitKind::Equal: {
2725 SourceLocation EqualLoc = ConsumeToken();
2726
2727 if (Tok.is(tok::kw_delete)) {
2728 if (D.isFunctionDeclarator())
2729 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2730 << 1 /* delete */;
2731 else
2732 Diag(ConsumeToken(), diag::err_deleted_non_function);
2733 SkipDeletedFunctionBody();
2734 } else if (Tok.is(tok::kw_default)) {
2735 if (D.isFunctionDeclarator())
2736 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2737 << 0 /* default */;
2738 else
2739 Diag(ConsumeToken(), diag::err_default_special_members)
2740 << getLangOpts().CPlusPlus20;
2741 } else {
2742 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2743
2744 if (Tok.is(tok::code_completion)) {
2745 cutOffParsing();
2747 ThisDecl);
2748 Actions.FinalizeDeclaration(ThisDecl);
2749 return nullptr;
2750 }
2751
2752 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2753 ExprResult Init = ParseInitializer();
2754
2755 // If this is the only decl in (possibly) range based for statement,
2756 // our best guess is that the user meant ':' instead of '='.
2757 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2758 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2759 << FixItHint::CreateReplacement(EqualLoc, ":");
2760 // We are trying to stop parser from looking for ';' in this for
2761 // statement, therefore preventing spurious errors to be issued.
2762 FRI->ColonLoc = EqualLoc;
2763 Init = ExprError();
2764 FRI->RangeExpr = Init;
2765 }
2766
2767 if (Init.isInvalid()) {
2769 StopTokens.push_back(tok::comma);
2772 StopTokens.push_back(tok::r_paren);
2773 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2774 Actions.ActOnInitializerError(ThisDecl);
2775 } else
2776 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2777 /*DirectInit=*/false);
2778 }
2779 break;
2780 }
2781 case InitKind::CXXDirect: {
2782 // Parse C++ direct initializer: '(' expression-list ')'
2783 BalancedDelimiterTracker T(*this, tok::l_paren);
2784 T.consumeOpen();
2785
2786 ExprVector Exprs;
2787
2788 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2789
2790 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2791 auto RunSignatureHelp = [&]() {
2792 QualType PreferredType =
2794 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2795 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2796 /*Braced=*/false);
2797 CalledSignatureHelp = true;
2798 return PreferredType;
2799 };
2800 auto SetPreferredType = [&] {
2801 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2802 };
2803
2804 llvm::function_ref<void()> ExpressionStarts;
2805 if (ThisVarDecl) {
2806 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2807 // VarDecl. This is an error and it is reported in a call to
2808 // Actions.ActOnInitializerError(). However, we call
2809 // ProduceConstructorSignatureHelp only on VarDecls.
2810 ExpressionStarts = SetPreferredType;
2811 }
2812
2813 bool SawError = ParseExpressionList(Exprs, ExpressionStarts);
2814
2815 if (SawError) {
2816 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2818 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2819 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2820 /*Braced=*/false);
2821 CalledSignatureHelp = true;
2822 }
2823 Actions.ActOnInitializerError(ThisDecl);
2824 SkipUntil(tok::r_paren, StopAtSemi);
2825 } else {
2826 // Match the ')'.
2827 T.consumeClose();
2828
2829 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2830 T.getCloseLocation(),
2831 Exprs);
2832 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2833 /*DirectInit=*/true);
2834 }
2835 break;
2836 }
2837 case InitKind::CXXBraced: {
2838 // Parse C++0x braced-init-list.
2839 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2840
2841 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2842
2843 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2844 ExprResult Init(ParseBraceInitializer());
2845
2846 if (Init.isInvalid()) {
2847 Actions.ActOnInitializerError(ThisDecl);
2848 } else
2849 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2850 break;
2851 }
2852 case InitKind::Uninitialized: {
2853 Actions.ActOnUninitializedDecl(ThisDecl);
2854 break;
2855 }
2856 }
2857
2858 Actions.FinalizeDeclaration(ThisDecl);
2859 return OuterDecl ? OuterDecl : ThisDecl;
2860}
2861
2862/// ParseSpecifierQualifierList
2863/// specifier-qualifier-list:
2864/// type-specifier specifier-qualifier-list[opt]
2865/// type-qualifier specifier-qualifier-list[opt]
2866/// [GNU] attributes specifier-qualifier-list[opt]
2867///
2868void Parser::ParseSpecifierQualifierList(
2869 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2870 AccessSpecifier AS, DeclSpecContext DSC) {
2871 ParsedTemplateInfo TemplateInfo;
2872 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2873 /// parse declaration-specifiers and complain about extra stuff.
2874 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2875 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC, nullptr,
2876 AllowImplicitTypename);
2877
2878 // Validate declspec for type-name.
2879 unsigned Specs = DS.getParsedSpecifiers();
2880 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2881 Diag(Tok, diag::err_expected_type);
2882 DS.SetTypeSpecError();
2883 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2884 Diag(Tok, diag::err_typename_requires_specqual);
2885 if (!DS.hasTypeSpecifier())
2886 DS.SetTypeSpecError();
2887 }
2888
2889 // Issue diagnostic and remove storage class if present.
2892 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2893 else
2895 diag::err_typename_invalid_storageclass);
2897 }
2898
2899 // Issue diagnostic and remove function specifier if present.
2900 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2901 if (DS.isInlineSpecified())
2902 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2903 if (DS.isVirtualSpecified())
2904 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2905 if (DS.hasExplicitSpecifier())
2906 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2907 if (DS.isNoreturnSpecified())
2908 Diag(DS.getNoreturnSpecLoc(), diag::err_typename_invalid_functionspec);
2909 DS.ClearFunctionSpecs();
2910 }
2911
2912 // Issue diagnostic and remove constexpr specifier if present.
2913 if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2914 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2915 << static_cast<int>(DS.getConstexprSpecifier());
2916 DS.ClearConstexprSpec();
2917 }
2918}
2919
2920/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2921/// specified token is valid after the identifier in a declarator which
2922/// immediately follows the declspec. For example, these things are valid:
2923///
2924/// int x [ 4]; // direct-declarator
2925/// int x ( int y); // direct-declarator
2926/// int(int x ) // direct-declarator
2927/// int x ; // simple-declaration
2928/// int x = 17; // init-declarator-list
2929/// int x , y; // init-declarator-list
2930/// int x __asm__ ("foo"); // init-declarator-list
2931/// int x : 4; // struct-declarator
2932/// int x { 5}; // C++'0x unified initializers
2933///
2934/// This is not, because 'x' does not immediately follow the declspec (though
2935/// ')' happens to be valid anyway).
2936/// int (x)
2937///
2939 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2940 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2941 tok::colon);
2942}
2943
2944/// ParseImplicitInt - This method is called when we have an non-typename
2945/// identifier in a declspec (which normally terminates the decl spec) when
2946/// the declspec has no type specifier. In this case, the declspec is either
2947/// malformed or is "implicit int" (in K&R and C89).
2948///
2949/// This method handles diagnosing this prettily and returns false if the
2950/// declspec is done being processed. If it recovers and thinks there may be
2951/// other pieces of declspec after it, it returns true.
2952///
2953bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2954 ParsedTemplateInfo &TemplateInfo,
2955 AccessSpecifier AS, DeclSpecContext DSC,
2956 ParsedAttributes &Attrs) {
2957 assert(Tok.is(tok::identifier) && "should have identifier");
2958
2960 // If we see an identifier that is not a type name, we normally would
2961 // parse it as the identifier being declared. However, when a typename
2962 // is typo'd or the definition is not included, this will incorrectly
2963 // parse the typename as the identifier name and fall over misparsing
2964 // later parts of the diagnostic.
2965 //
2966 // As such, we try to do some look-ahead in cases where this would
2967 // otherwise be an "implicit-int" case to see if this is invalid. For
2968 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2969 // an identifier with implicit int, we'd get a parse error because the
2970 // next token is obviously invalid for a type. Parse these as a case
2971 // with an invalid type specifier.
2972 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2973
2974 // Since we know that this either implicit int (which is rare) or an
2975 // error, do lookahead to try to do better recovery. This never applies
2976 // within a type specifier. Outside of C++, we allow this even if the
2977 // language doesn't "officially" support implicit int -- we support
2978 // implicit int as an extension in some language modes.
2979 if (!isTypeSpecifier(DSC) && getLangOpts().isImplicitIntAllowed() &&
2981 // If this token is valid for implicit int, e.g. "static x = 4", then
2982 // we just avoid eating the identifier, so it will be parsed as the
2983 // identifier in the declarator.
2984 return false;
2985 }
2986
2987 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2988 // for incomplete declarations such as `pipe p`.
2989 if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2990 return false;
2991
2992 if (getLangOpts().CPlusPlus &&
2994 // Don't require a type specifier if we have the 'auto' storage class
2995 // specifier in C++98 -- we'll promote it to a type specifier.
2996 if (SS)
2997 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2998 return false;
2999 }
3000
3001 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
3002 getLangOpts().MSVCCompat) {
3003 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
3004 // Give Sema a chance to recover if we are in a template with dependent base
3005 // classes.
3007 *Tok.getIdentifierInfo(), Tok.getLocation(),
3008 DSC == DeclSpecContext::DSC_template_type_arg)) {
3009 const char *PrevSpec;
3010 unsigned DiagID;
3011 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
3012 Actions.getASTContext().getPrintingPolicy());
3013 DS.SetRangeEnd(Tok.getLocation());
3014 ConsumeToken();
3015 return false;
3016 }
3017 }
3018
3019 // Otherwise, if we don't consume this token, we are going to emit an
3020 // error anyway. Try to recover from various common problems. Check
3021 // to see if this was a reference to a tag name without a tag specified.
3022 // This is a common problem in C (saying 'foo' instead of 'struct foo').
3023 //
3024 // C++ doesn't need this, and isTagName doesn't take SS.
3025 if (SS == nullptr) {
3026 const char *TagName = nullptr, *FixitTagName = nullptr;
3027 tok::TokenKind TagKind = tok::unknown;
3028
3029 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
3030 default: break;
3031 case DeclSpec::TST_enum:
3032 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
3034 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
3036 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
3038 TagName="__interface"; FixitTagName = "__interface ";
3039 TagKind=tok::kw___interface;break;
3041 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
3042 }
3043
3044 if (TagName) {
3045 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
3046 LookupResult R(Actions, TokenName, SourceLocation(),
3048
3049 Diag(Loc, diag::err_use_of_tag_name_without_tag)
3050 << TokenName << TagName << getLangOpts().CPlusPlus
3051 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
3052
3053 if (Actions.LookupName(R, getCurScope())) {
3054 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
3055 I != IEnd; ++I)
3056 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
3057 << TokenName << TagName;
3058 }
3059
3060 // Parse this as a tag as if the missing tag were present.
3061 if (TagKind == tok::kw_enum)
3062 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
3063 DeclSpecContext::DSC_normal);
3064 else
3065 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
3066 /*EnteringContext*/ false,
3067 DeclSpecContext::DSC_normal, Attrs);
3068 return true;
3069 }
3070 }
3071
3072 // Determine whether this identifier could plausibly be the name of something
3073 // being declared (with a missing type).
3074 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
3075 DSC == DeclSpecContext::DSC_class)) {
3076 // Look ahead to the next token to try to figure out what this declaration
3077 // was supposed to be.
3078 switch (NextToken().getKind()) {
3079 case tok::l_paren: {
3080 // static x(4); // 'x' is not a type
3081 // x(int n); // 'x' is not a type
3082 // x (*p)[]; // 'x' is a type
3083 //
3084 // Since we're in an error case, we can afford to perform a tentative
3085 // parse to determine which case we're in.
3086 TentativeParsingAction PA(*this);
3087 ConsumeToken();
3088 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
3089 PA.Revert();
3090
3091 if (TPR != TPResult::False) {
3092 // The identifier is followed by a parenthesized declarator.
3093 // It's supposed to be a type.
3094 break;
3095 }
3096
3097 // If we're in a context where we could be declaring a constructor,
3098 // check whether this is a constructor declaration with a bogus name.
3099 if (DSC == DeclSpecContext::DSC_class ||
3100 (DSC == DeclSpecContext::DSC_top_level && SS)) {
3102 if (Actions.isCurrentClassNameTypo(II, SS)) {
3103 Diag(Loc, diag::err_constructor_bad_name)
3104 << Tok.getIdentifierInfo() << II
3106 Tok.setIdentifierInfo(II);
3107 }
3108 }
3109 // Fall through.
3110 [[fallthrough]];
3111 }
3112 case tok::comma:
3113 case tok::equal:
3114 case tok::kw_asm:
3115 case tok::l_brace:
3116 case tok::l_square:
3117 case tok::semi:
3118 // This looks like a variable or function declaration. The type is
3119 // probably missing. We're done parsing decl-specifiers.
3120 // But only if we are not in a function prototype scope.
3121 if (getCurScope()->isFunctionPrototypeScope())
3122 break;
3123 if (SS)
3124 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
3125 return false;
3126
3127 default:
3128 // This is probably supposed to be a type. This includes cases like:
3129 // int f(itn);
3130 // struct S { unsigned : 4; };
3131 break;
3132 }
3133 }
3134
3135 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
3136 // and attempt to recover.
3137 ParsedType T;
3139 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
3140 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
3141 IsTemplateName);
3142 if (T) {
3143 // The action has suggested that the type T could be used. Set that as
3144 // the type in the declaration specifiers, consume the would-be type
3145 // name token, and we're done.
3146 const char *PrevSpec;
3147 unsigned DiagID;
3148 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
3149 Actions.getASTContext().getPrintingPolicy());
3150 DS.SetRangeEnd(Tok.getLocation());
3151 ConsumeToken();
3152 // There may be other declaration specifiers after this.
3153 return true;
3154 } else if (II != Tok.getIdentifierInfo()) {
3155 // If no type was suggested, the correction is to a keyword
3156 Tok.setKind(II->getTokenID());
3157 // There may be other declaration specifiers after this.
3158 return true;
3159 }
3160
3161 // Otherwise, the action had no suggestion for us. Mark this as an error.
3162 DS.SetTypeSpecError();
3163 DS.SetRangeEnd(Tok.getLocation());
3164 ConsumeToken();
3165
3166 // Eat any following template arguments.
3167 if (IsTemplateName) {
3168 SourceLocation LAngle, RAngle;
3169 TemplateArgList Args;
3170 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
3171 }
3172
3173 // TODO: Could inject an invalid typedef decl in an enclosing scope to
3174 // avoid rippling error messages on subsequent uses of the same type,
3175 // could be useful if #include was forgotten.
3176 return true;
3177}
3178
3179/// Determine the declaration specifier context from the declarator
3180/// context.
3181///
3182/// \param Context the declarator context, which is one of the
3183/// DeclaratorContext enumerator values.
3184Parser::DeclSpecContext
3185Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
3186 switch (Context) {
3188 return DeclSpecContext::DSC_class;
3190 return DeclSpecContext::DSC_top_level;
3192 return DeclSpecContext::DSC_template_param;
3194 return DeclSpecContext::DSC_template_arg;
3196 return DeclSpecContext::DSC_template_type_arg;
3199 return DeclSpecContext::DSC_trailing;
3202 return DeclSpecContext::DSC_alias_declaration;
3204 return DeclSpecContext::DSC_association;
3206 return DeclSpecContext::DSC_type_specifier;
3208 return DeclSpecContext::DSC_condition;
3210 return DeclSpecContext::DSC_conv_operator;
3212 return DeclSpecContext::DSC_new;
3227 return DeclSpecContext::DSC_normal;
3228 }
3229
3230 llvm_unreachable("Missing DeclaratorContext case");
3231}
3232
3233/// ParseAlignArgument - Parse the argument to an alignment-specifier.
3234///
3235/// [C11] type-id
3236/// [C11] constant-expression
3237/// [C++0x] type-id ...[opt]
3238/// [C++0x] assignment-expression ...[opt]
3239ExprResult Parser::ParseAlignArgument(StringRef KWName, SourceLocation Start,
3240 SourceLocation &EllipsisLoc, bool &IsType,
3242 ExprResult ER;
3243 if (isTypeIdInParens()) {
3245 ParsedType Ty = ParseTypeName().get();
3246 SourceRange TypeRange(Start, Tok.getLocation());
3247 if (Actions.ActOnAlignasTypeArgument(KWName, Ty, TypeLoc, TypeRange))
3248 return ExprError();
3249 TypeResult = Ty;
3250 IsType = true;
3251 } else {
3253 IsType = false;
3254 }
3255
3257 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3258
3259 return ER;
3260}
3261
3262/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
3263/// attribute to Attrs.
3264///
3265/// alignment-specifier:
3266/// [C11] '_Alignas' '(' type-id ')'
3267/// [C11] '_Alignas' '(' constant-expression ')'
3268/// [C++11] 'alignas' '(' type-id ...[opt] ')'
3269/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
3270void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
3271 SourceLocation *EndLoc) {
3272 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
3273 "Not an alignment-specifier!");
3274 Token KWTok = Tok;
3275 IdentifierInfo *KWName = KWTok.getIdentifierInfo();
3276 auto Kind = KWTok.getKind();
3277 SourceLocation KWLoc = ConsumeToken();
3278
3279 BalancedDelimiterTracker T(*this, tok::l_paren);
3280 if (T.expectAndConsume())
3281 return;
3282
3283 bool IsType;
3285 SourceLocation EllipsisLoc;
3286 ExprResult ArgExpr =
3287 ParseAlignArgument(PP.getSpelling(KWTok), T.getOpenLocation(),
3288 EllipsisLoc, IsType, TypeResult);
3289 if (ArgExpr.isInvalid()) {
3290 T.skipToEnd();
3291 return;
3292 }
3293
3294 T.consumeClose();
3295 if (EndLoc)
3296 *EndLoc = T.getCloseLocation();
3297
3298 if (IsType) {
3299 Attrs.addNewTypeAttr(KWName, KWLoc, nullptr, KWLoc, TypeResult, Kind,
3300 EllipsisLoc);
3301 } else {
3302 ArgsVector ArgExprs;
3303 ArgExprs.push_back(ArgExpr.get());
3304 Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1, Kind,
3305 EllipsisLoc);
3306 }
3307}
3308
3309/// Bounds attributes (e.g., counted_by):
3310/// AttrName '(' expression ')'
3311void Parser::ParseBoundsAttribute(IdentifierInfo &AttrName,
3312 SourceLocation AttrNameLoc,
3313 ParsedAttributes &Attrs,
3314 IdentifierInfo *ScopeName,
3315 SourceLocation ScopeLoc,
3316 ParsedAttr::Form Form) {
3317 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
3318
3319 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3320 Parens.consumeOpen();
3321
3322 if (Tok.is(tok::r_paren)) {
3323 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
3324 Parens.consumeClose();
3325 return;
3326 }
3327
3328 ArgsVector ArgExprs;
3329 // Don't evaluate argument when the attribute is ignored.
3330 using ExpressionKind =
3334 ExpressionKind::EK_BoundsAttrArgument);
3335
3336 ExprResult ArgExpr(
3338
3339 if (ArgExpr.isInvalid()) {
3340 Parens.skipToEnd();
3341 return;
3342 }
3343
3344 ArgExprs.push_back(ArgExpr.get());
3345 Parens.consumeClose();
3346
3347 ASTContext &Ctx = Actions.getASTContext();
3348
3349 ArgExprs.push_back(IntegerLiteral::Create(
3350 Ctx, llvm::APInt(Ctx.getTypeSize(Ctx.getSizeType()), 0),
3351 Ctx.getSizeType(), SourceLocation()));
3352
3353 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
3354 ScopeName, ScopeLoc, ArgExprs.data(), ArgExprs.size(), Form);
3355}
3356
3357ExprResult Parser::ParseExtIntegerArgument() {
3358 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
3359 "Not an extended int type");
3360 ConsumeToken();
3361
3362 BalancedDelimiterTracker T(*this, tok::l_paren);
3363 if (T.expectAndConsume())
3364 return ExprError();
3365
3367 if (ER.isInvalid()) {
3368 T.skipToEnd();
3369 return ExprError();
3370 }
3371
3372 if(T.consumeClose())
3373 return ExprError();
3374 return ER;
3375}
3376
3377/// Determine whether we're looking at something that might be a declarator
3378/// in a simple-declaration. If it can't possibly be a declarator, maybe
3379/// diagnose a missing semicolon after a prior tag definition in the decl
3380/// specifier.
3381///
3382/// \return \c true if an error occurred and this can't be any kind of
3383/// declaration.
3384bool
3385Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
3386 DeclSpecContext DSContext,
3387 LateParsedAttrList *LateAttrs) {
3388 assert(DS.hasTagDefinition() && "shouldn't call this");
3389
3390 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3391 DSContext == DeclSpecContext::DSC_top_level);
3392
3393 if (getLangOpts().CPlusPlus &&
3394 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
3395 tok::annot_template_id) &&
3396 TryAnnotateCXXScopeToken(EnteringContext)) {
3398 return true;
3399 }
3400
3401 bool HasScope = Tok.is(tok::annot_cxxscope);
3402 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
3403 Token AfterScope = HasScope ? NextToken() : Tok;
3404
3405 // Determine whether the following tokens could possibly be a
3406 // declarator.
3407 bool MightBeDeclarator = true;
3408 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
3409 // A declarator-id can't start with 'typename'.
3410 MightBeDeclarator = false;
3411 } else if (AfterScope.is(tok::annot_template_id)) {
3412 // If we have a type expressed as a template-id, this cannot be a
3413 // declarator-id (such a type cannot be redeclared in a simple-declaration).
3414 TemplateIdAnnotation *Annot =
3415 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
3416 if (Annot->Kind == TNK_Type_template)
3417 MightBeDeclarator = false;
3418 } else if (AfterScope.is(tok::identifier)) {
3419 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
3420
3421 // These tokens cannot come after the declarator-id in a
3422 // simple-declaration, and are likely to come after a type-specifier.
3423 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
3424 tok::annot_cxxscope, tok::coloncolon)) {
3425 // Missing a semicolon.
3426 MightBeDeclarator = false;
3427 } else if (HasScope) {
3428 // If the declarator-id has a scope specifier, it must redeclare a
3429 // previously-declared entity. If that's a type (and this is not a
3430 // typedef), that's an error.
3431 CXXScopeSpec SS;
3433 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3434 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
3435 Sema::NameClassification Classification = Actions.ClassifyName(
3436 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
3437 /*CCC=*/nullptr);
3438 switch (Classification.getKind()) {
3439 case Sema::NC_Error:
3441 return true;
3442
3443 case Sema::NC_Keyword:
3444 llvm_unreachable("typo correction is not possible here");
3445
3446 case Sema::NC_Type:
3450 // Not a previously-declared non-type entity.
3451 MightBeDeclarator = false;
3452 break;
3453
3454 case Sema::NC_Unknown:
3455 case Sema::NC_NonType:
3460 case Sema::NC_Concept:
3461 // Might be a redeclaration of a prior entity.
3462 break;
3463 }
3464 }
3465 }
3466
3467 if (MightBeDeclarator)
3468 return false;
3469
3470 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
3472 diag::err_expected_after)
3473 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
3474
3475 // Try to recover from the typo, by dropping the tag definition and parsing
3476 // the problematic tokens as a type.
3477 //
3478 // FIXME: Split the DeclSpec into pieces for the standalone
3479 // declaration and pieces for the following declaration, instead
3480 // of assuming that all the other pieces attach to new declaration,
3481 // and call ParsedFreeStandingDeclSpec as appropriate.
3482 DS.ClearTypeSpecType();
3483 ParsedTemplateInfo NotATemplate;
3484 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
3485 return false;
3486}
3487
3488/// ParseDeclarationSpecifiers
3489/// declaration-specifiers: [C99 6.7]
3490/// storage-class-specifier declaration-specifiers[opt]
3491/// type-specifier declaration-specifiers[opt]
3492/// [C99] function-specifier declaration-specifiers[opt]
3493/// [C11] alignment-specifier declaration-specifiers[opt]
3494/// [GNU] attributes declaration-specifiers[opt]
3495/// [Clang] '__module_private__' declaration-specifiers[opt]
3496/// [ObjC1] '__kindof' declaration-specifiers[opt]
3497///
3498/// storage-class-specifier: [C99 6.7.1]
3499/// 'typedef'
3500/// 'extern'
3501/// 'static'
3502/// 'auto'
3503/// 'register'
3504/// [C++] 'mutable'
3505/// [C++11] 'thread_local'
3506/// [C11] '_Thread_local'
3507/// [GNU] '__thread'
3508/// function-specifier: [C99 6.7.4]
3509/// [C99] 'inline'
3510/// [C++] 'virtual'
3511/// [C++] 'explicit'
3512/// [OpenCL] '__kernel'
3513/// 'friend': [C++ dcl.friend]
3514/// 'constexpr': [C++0x dcl.constexpr]
3515void Parser::ParseDeclarationSpecifiers(
3516 DeclSpec &DS, ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
3517 DeclSpecContext DSContext, LateParsedAttrList *LateAttrs,
3518 ImplicitTypenameContext AllowImplicitTypename) {
3519 if (DS.getSourceRange().isInvalid()) {
3520 // Start the range at the current token but make the end of the range
3521 // invalid. This will make the entire range invalid unless we successfully
3522 // consume a token.
3523 DS.SetRangeStart(Tok.getLocation());
3525 }
3526
3527 // If we are in a operator context, convert it back into a type specifier
3528 // context for better error handling later on.
3529 if (DSContext == DeclSpecContext::DSC_conv_operator) {
3530 // No implicit typename here.
3531 AllowImplicitTypename = ImplicitTypenameContext::No;
3532 DSContext = DeclSpecContext::DSC_type_specifier;
3533 }
3534
3535 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3536 DSContext == DeclSpecContext::DSC_top_level);
3537 bool AttrsLastTime = false;
3538 ParsedAttributes attrs(AttrFactory);
3539 // We use Sema's policy to get bool macros right.
3540 PrintingPolicy Policy = Actions.getPrintingPolicy();
3541 while (true) {
3542 bool isInvalid = false;
3543 bool isStorageClass = false;
3544 const char *PrevSpec = nullptr;
3545 unsigned DiagID = 0;
3546
3547 // This value needs to be set to the location of the last token if the last
3548 // token of the specifier is already consumed.
3549 SourceLocation ConsumedEnd;
3550
3551 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3552 // implementation for VS2013 uses _Atomic as an identifier for one of the
3553 // classes in <atomic>.
3554 //
3555 // A typedef declaration containing _Atomic<...> is among the places where
3556 // the class is used. If we are currently parsing such a declaration, treat
3557 // the token as an identifier.
3558 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3560 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3561 Tok.setKind(tok::identifier);
3562
3564
3565 // Helper for image types in OpenCL.
3566 auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
3567 // Check if the image type is supported and otherwise turn the keyword into an identifier
3568 // because image types from extensions are not reserved identifiers.
3569 if (!StringRef(Ext).empty() && !getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())) {
3571 Tok.setKind(tok::identifier);
3572 return false;
3573 }
3574 isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3575 return true;
3576 };
3577
3578 // Turn off usual access checking for template specializations and
3579 // instantiations.
3580 bool IsTemplateSpecOrInst =
3581 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3582 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3583
3584 switch (Tok.getKind()) {
3585 default:
3586 if (Tok.isRegularKeywordAttribute())
3587 goto Attribute;
3588
3589 DoneWithDeclSpec:
3590 if (!AttrsLastTime)
3591 ProhibitAttributes(attrs);
3592 else {
3593 // Reject C++11 / C23 attributes that aren't type attributes.
3594 for (const ParsedAttr &PA : attrs) {
3595 if (!PA.isCXX11Attribute() && !PA.isC23Attribute() &&
3596 !PA.isRegularKeywordAttribute())
3597 continue;
3598 if (PA.getKind() == ParsedAttr::UnknownAttribute)
3599 // We will warn about the unknown attribute elsewhere (in
3600 // SemaDeclAttr.cpp)
3601 continue;
3602 // GCC ignores this attribute when placed on the DeclSpec in [[]]
3603 // syntax, so we do the same.
3604 if (PA.getKind() == ParsedAttr::AT_VectorSize) {
3605 Diag(PA.getLoc(), diag::warn_attribute_ignored) << PA;
3606 PA.setInvalid();
3607 continue;
3608 }
3609 // We reject AT_LifetimeBound and AT_AnyX86NoCfCheck, even though they
3610 // are type attributes, because we historically haven't allowed these
3611 // to be used as type attributes in C++11 / C23 syntax.
3612 if (PA.isTypeAttr() && PA.getKind() != ParsedAttr::AT_LifetimeBound &&
3613 PA.getKind() != ParsedAttr::AT_AnyX86NoCfCheck)
3614 continue;
3615 Diag(PA.getLoc(), diag::err_attribute_not_type_attr)
3616 << PA << PA.isRegularKeywordAttribute();
3617 PA.setInvalid();
3618 }
3619
3620 DS.takeAttributesFrom(attrs);
3621 }
3622
3623 // If this is not a declaration specifier token, we're done reading decl
3624 // specifiers. First verify that DeclSpec's are consistent.
3625 DS.Finish(Actions, Policy);
3626 return;
3627
3628 // alignment-specifier
3629 case tok::kw__Alignas:
3630 diagnoseUseOfC11Keyword(Tok);
3631 [[fallthrough]];
3632 case tok::kw_alignas:
3633 // _Alignas and alignas (C23, not C++) should parse the same way. The C++
3634 // parsing for alignas happens through the usual attribute parsing. This
3635 // ensures that an alignas specifier can appear in a type position in C
3636 // despite that not being valid in C++.
3637 if (getLangOpts().C23 || Tok.getKind() == tok::kw__Alignas) {
3638 if (Tok.getKind() == tok::kw_alignas)
3639 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
3640 ParseAlignmentSpecifier(DS.getAttributes());
3641 continue;
3642 }
3643 [[fallthrough]];
3644 case tok::l_square:
3645 if (!isAllowedCXX11AttributeSpecifier())
3646 goto DoneWithDeclSpec;
3647
3648 Attribute:
3649 ProhibitAttributes(attrs);
3650 // FIXME: It would be good to recover by accepting the attributes,
3651 // but attempting to do that now would cause serious
3652 // madness in terms of diagnostics.
3653 attrs.clear();
3654 attrs.Range = SourceRange();
3655
3656 ParseCXX11Attributes(attrs);
3657 AttrsLastTime = true;
3658 continue;
3659
3660 case tok::code_completion: {
3663 if (DS.hasTypeSpecifier()) {
3664 bool AllowNonIdentifiers
3669 Scope::AtCatchScope)) == 0;
3670 bool AllowNestedNameSpecifiers
3671 = DSContext == DeclSpecContext::DSC_top_level ||
3672 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3673
3674 cutOffParsing();
3676 getCurScope(), DS, AllowNonIdentifiers, AllowNestedNameSpecifiers);
3677 return;
3678 }
3679
3680 // Class context can appear inside a function/block, so prioritise that.
3681 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3682 CCC = DSContext == DeclSpecContext::DSC_class
3685 else if (DSContext == DeclSpecContext::DSC_class)
3687 else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3689 else if (CurParsedObjCImpl)
3691
3692 cutOffParsing();
3694 return;
3695 }
3696
3697 case tok::coloncolon: // ::foo::bar
3698 // C++ scope specifier. Annotate and loop, or bail out on error.
3699 if (getLangOpts().CPlusPlus &&
3700 TryAnnotateCXXScopeToken(EnteringContext)) {
3701 if (!DS.hasTypeSpecifier())
3702 DS.SetTypeSpecError();
3703 goto DoneWithDeclSpec;
3704 }
3705 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3706 goto DoneWithDeclSpec;
3707 continue;
3708
3709 case tok::annot_cxxscope: {
3710 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3711 goto DoneWithDeclSpec;
3712
3713 CXXScopeSpec SS;
3714 if (TemplateInfo.TemplateParams)
3715 SS.setTemplateParamLists(*TemplateInfo.TemplateParams);
3717 Tok.getAnnotationRange(),
3718 SS);
3719
3720 // We are looking for a qualified typename.
3721 Token Next = NextToken();
3722
3723 TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3724 ? takeTemplateIdAnnotation(Next)
3725 : nullptr;
3726 if (TemplateId && TemplateId->hasInvalidName()) {
3727 // We found something like 'T::U<Args> x', but U is not a template.
3728 // Assume it was supposed to be a type.
3729 DS.SetTypeSpecError();
3730 ConsumeAnnotationToken();
3731 break;
3732 }
3733
3734 if (TemplateId && TemplateId->Kind == TNK_Type_template) {
3735 // We have a qualified template-id, e.g., N::A<int>
3736
3737 // If this would be a valid constructor declaration with template
3738 // arguments, we will reject the attempt to form an invalid type-id
3739 // referring to the injected-class-name when we annotate the token,
3740 // per C++ [class.qual]p2.
3741 //
3742 // To improve diagnostics for this case, parse the declaration as a
3743 // constructor (and reject the extra template arguments later).
3744 if ((DSContext == DeclSpecContext::DSC_top_level ||
3745 DSContext == DeclSpecContext::DSC_class) &&
3746 TemplateId->Name &&
3747 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3748 isConstructorDeclarator(/*Unqualified=*/false,
3749 /*DeductionGuide=*/false,
3750 DS.isFriendSpecified())) {
3751 // The user meant this to be an out-of-line constructor
3752 // definition, but template arguments are not allowed
3753 // there. Just allow this as a constructor; we'll
3754 // complain about it later.
3755 goto DoneWithDeclSpec;
3756 }
3757
3758 DS.getTypeSpecScope() = SS;
3759 ConsumeAnnotationToken(); // The C++ scope.
3760 assert(Tok.is(tok::annot_template_id) &&
3761 "ParseOptionalCXXScopeSpecifier not working");
3762 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3763 continue;
3764 }
3765
3766 if (TemplateId && TemplateId->Kind == TNK_Concept_template) {
3767 DS.getTypeSpecScope() = SS;
3768 // This is probably a qualified placeholder-specifier, e.g., ::C<int>
3769 // auto ... Consume the scope annotation and continue to consume the
3770 // template-id as a placeholder-specifier. Let the next iteration
3771 // diagnose a missing auto.
3772 ConsumeAnnotationToken();
3773 continue;
3774 }
3775
3776 if (Next.is(tok::annot_typename)) {
3777 DS.getTypeSpecScope() = SS;
3778 ConsumeAnnotationToken(); // The C++ scope.
3781 Tok.getAnnotationEndLoc(),
3782 PrevSpec, DiagID, T, Policy);
3783 if (isInvalid)
3784 break;
3786 ConsumeAnnotationToken(); // The typename
3787 }
3788
3789 if (AllowImplicitTypename == ImplicitTypenameContext::Yes &&
3790 Next.is(tok::annot_template_id) &&
3791 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3793 DS.getTypeSpecScope() = SS;
3794 ConsumeAnnotationToken(); // The C++ scope.
3795 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3796 continue;
3797 }
3798
3799 if (Next.isNot(tok::identifier))
3800 goto DoneWithDeclSpec;
3801
3802 // Check whether this is a constructor declaration. If we're in a
3803 // context where the identifier could be a class name, and it has the
3804 // shape of a constructor declaration, process it as one.
3805 if ((DSContext == DeclSpecContext::DSC_top_level ||
3806 DSContext == DeclSpecContext::DSC_class) &&
3807 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3808 &SS) &&
3809 isConstructorDeclarator(/*Unqualified=*/false,
3810 /*DeductionGuide=*/false,
3811 DS.isFriendSpecified(),
3812 &TemplateInfo))
3813 goto DoneWithDeclSpec;
3814
3815 // C++20 [temp.spec] 13.9/6.
3816 // This disables the access checking rules for function template explicit
3817 // instantiation and explicit specialization:
3818 // - `return type`.
3819 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3820
3821 ParsedType TypeRep = Actions.getTypeName(
3822 *Next.getIdentifierInfo(), Next.getLocation(), getCurScope(), &SS,
3823 false, false, nullptr,
3824 /*IsCtorOrDtorName=*/false,
3825 /*WantNontrivialTypeSourceInfo=*/true,
3826 isClassTemplateDeductionContext(DSContext), AllowImplicitTypename);
3827
3828 if (IsTemplateSpecOrInst)
3829 SAC.done();
3830
3831 // If the referenced identifier is not a type, then this declspec is
3832 // erroneous: We already checked about that it has no type specifier, and
3833 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3834 // typename.
3835 if (!TypeRep) {
3836 if (TryAnnotateTypeConstraint())
3837 goto DoneWithDeclSpec;
3838 if (Tok.isNot(tok::annot_cxxscope) ||
3839 NextToken().isNot(tok::identifier))
3840 continue;
3841 // Eat the scope spec so the identifier is current.
3842 ConsumeAnnotationToken();
3843 ParsedAttributes Attrs(AttrFactory);
3844 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3845 if (!Attrs.empty()) {
3846 AttrsLastTime = true;
3847 attrs.takeAllFrom(Attrs);
3848 }
3849 continue;
3850 }
3851 goto DoneWithDeclSpec;
3852 }
3853
3854 DS.getTypeSpecScope() = SS;
3855 ConsumeAnnotationToken(); // The C++ scope.
3856
3858 DiagID, TypeRep, Policy);
3859 if (isInvalid)
3860 break;
3861
3862 DS.SetRangeEnd(Tok.getLocation());
3863 ConsumeToken(); // The typename.
3864
3865 continue;
3866 }
3867
3868 case tok::annot_typename: {
3869 // If we've previously seen a tag definition, we were almost surely
3870 // missing a semicolon after it.
3871 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3872 goto DoneWithDeclSpec;
3873
3876 DiagID, T, Policy);
3877 if (isInvalid)
3878 break;
3879
3881 ConsumeAnnotationToken(); // The typename
3882
3883 continue;
3884 }
3885
3886 case tok::kw___is_signed:
3887 // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3888 // typically treats it as a trait. If we see __is_signed as it appears
3889 // in libstdc++, e.g.,
3890 //
3891 // static const bool __is_signed;
3892 //
3893 // then treat __is_signed as an identifier rather than as a keyword.
3894 if (DS.getTypeSpecType() == TST_bool &&
3897 TryKeywordIdentFallback(true);
3898
3899 // We're done with the declaration-specifiers.
3900 goto DoneWithDeclSpec;
3901
3902 // typedef-name
3903 case tok::kw___super:
3904 case tok::kw_decltype:
3905 case tok::identifier:
3906 ParseIdentifier: {
3907 // This identifier can only be a typedef name if we haven't already seen
3908 // a type-specifier. Without this check we misparse:
3909 // typedef int X; struct Y { short X; }; as 'short int'.
3910 if (DS.hasTypeSpecifier())
3911 goto DoneWithDeclSpec;
3912
3913 // If the token is an identifier named "__declspec" and Microsoft
3914 // extensions are not enabled, it is likely that there will be cascading
3915 // parse errors if this really is a __declspec attribute. Attempt to
3916 // recognize that scenario and recover gracefully.
3917 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3918 Tok.getIdentifierInfo()->getName() == "__declspec") {
3919 Diag(Loc, diag::err_ms_attributes_not_enabled);
3920
3921 // The next token should be an open paren. If it is, eat the entire
3922 // attribute declaration and continue.
3923 if (NextToken().is(tok::l_paren)) {
3924 // Consume the __declspec identifier.
3925 ConsumeToken();
3926
3927 // Eat the parens and everything between them.
3928 BalancedDelimiterTracker T(*this, tok::l_paren);
3929 if (T.consumeOpen()) {
3930 assert(false && "Not a left paren?");
3931 return;
3932 }
3933 T.skipToEnd();
3934 continue;
3935 }
3936 }
3937
3938 // In C++, check to see if this is a scope specifier like foo::bar::, if
3939 // so handle it as such. This is important for ctor parsing.
3940 if (getLangOpts().CPlusPlus) {
3941 // C++20 [temp.spec] 13.9/6.
3942 // This disables the access checking rules for function template
3943 // explicit instantiation and explicit specialization:
3944 // - `return type`.
3945 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3946
3947 const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
3948
3949 if (IsTemplateSpecOrInst)
3950 SAC.done();
3951
3952 if (Success) {
3953 if (IsTemplateSpecOrInst)
3954 SAC.redelay();
3955 DS.SetTypeSpecError();
3956 goto DoneWithDeclSpec;
3957 }
3958
3959 if (!Tok.is(tok::identifier))
3960 continue;
3961 }
3962
3963 // Check for need to substitute AltiVec keyword tokens.
3964 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3965 break;
3966
3967 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3968 // allow the use of a typedef name as a type specifier.
3969 if (DS.isTypeAltiVecVector())
3970 goto DoneWithDeclSpec;
3971
3972 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3973 isObjCInstancetype()) {
3974 ParsedType TypeRep = Actions.ObjC().ActOnObjCInstanceType(Loc);
3975 assert(TypeRep);
3977 DiagID, TypeRep, Policy);
3978 if (isInvalid)
3979 break;
3980
3981 DS.SetRangeEnd(Loc);
3982 ConsumeToken();
3983 continue;
3984 }
3985
3986 // If we're in a context where the identifier could be a class name,
3987 // check whether this is a constructor declaration.
3988 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3990 isConstructorDeclarator(/*Unqualified=*/true,
3991 /*DeductionGuide=*/false,
3992 DS.isFriendSpecified()))
3993 goto DoneWithDeclSpec;
3994
3995 ParsedType TypeRep = Actions.getTypeName(
3996 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3997 false, false, nullptr, false, false,
3998 isClassTemplateDeductionContext(DSContext));
3999
4000 // If this is not a typedef name, don't parse it as part of the declspec,
4001 // it must be an implicit int or an error.
4002 if (!TypeRep) {
4003 if (TryAnnotateTypeConstraint())
4004 goto DoneWithDeclSpec;
4005 if (Tok.isNot(tok::identifier))
4006 continue;
4007 ParsedAttributes Attrs(AttrFactory);
4008 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
4009 if (!Attrs.empty()) {
4010 AttrsLastTime = true;
4011 attrs.takeAllFrom(Attrs);
4012 }
4013 continue;
4014 }
4015 goto DoneWithDeclSpec;
4016 }
4017
4018 // Likewise, if this is a context where the identifier could be a template
4019 // name, check whether this is a deduction guide declaration.
4020 CXXScopeSpec SS;
4021 if (getLangOpts().CPlusPlus17 &&
4022 (DSContext == DeclSpecContext::DSC_class ||
4023 DSContext == DeclSpecContext::DSC_top_level) &&
4025 Tok.getLocation(), SS) &&
4026 isConstructorDeclarator(/*Unqualified*/ true,
4027 /*DeductionGuide*/ true))
4028 goto DoneWithDeclSpec;
4029
4031 DiagID, TypeRep, Policy);
4032 if (isInvalid)
4033 break;
4034
4035 DS.SetRangeEnd(Tok.getLocation());
4036 ConsumeToken(); // The identifier
4037
4038 // Objective-C supports type arguments and protocol references
4039 // following an Objective-C object or object pointer
4040 // type. Handle either one of them.
4041 if (Tok.is(tok::less) && getLangOpts().ObjC) {
4042 SourceLocation NewEndLoc;
4043 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
4044 Loc, TypeRep, /*consumeLastToken=*/true,
4045 NewEndLoc);
4046 if (NewTypeRep.isUsable()) {
4047 DS.UpdateTypeRep(NewTypeRep.get());
4048 DS.SetRangeEnd(NewEndLoc);
4049 }
4050 }
4051
4052 // Need to support trailing type qualifiers (e.g. "id<p> const").
4053 // If a type specifier follows, it will be diagnosed elsewhere.
4054 continue;
4055 }
4056
4057 // type-name or placeholder-specifier
4058 case tok::annot_template_id: {
4059 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
4060
4061 if (TemplateId->hasInvalidName()) {
4062 DS.SetTypeSpecError();
4063 break;
4064 }
4065
4066 if (TemplateId->Kind == TNK_Concept_template) {
4067 // If we've already diagnosed that this type-constraint has invalid
4068 // arguments, drop it and just form 'auto' or 'decltype(auto)'.
4069 if (TemplateId->hasInvalidArgs())
4070 TemplateId = nullptr;
4071
4072 // Any of the following tokens are likely the start of the user
4073 // forgetting 'auto' or 'decltype(auto)', so diagnose.
4074 // Note: if updating this list, please make sure we update
4075 // isCXXDeclarationSpecifier's check for IsPlaceholderSpecifier to have
4076 // a matching list.
4077 if (NextToken().isOneOf(tok::identifier, tok::kw_const,
4078 tok::kw_volatile, tok::kw_restrict, tok::amp,
4079 tok::ampamp)) {
4080 Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
4081 << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
4082 // Attempt to continue as if 'auto' was placed here.
4083 isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
4084 TemplateId, Policy);
4085 break;
4086 }
4087 if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
4088 goto DoneWithDeclSpec;
4089
4090 if (TemplateId && !isInvalid && Actions.CheckTypeConstraint(TemplateId))
4091 TemplateId = nullptr;
4092
4093 ConsumeAnnotationToken();
4094 SourceLocation AutoLoc = Tok.getLocation();
4095 if (TryConsumeToken(tok::kw_decltype)) {
4096 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4097 if (Tracker.consumeOpen()) {
4098 // Something like `void foo(Iterator decltype i)`
4099 Diag(Tok, diag::err_expected) << tok::l_paren;
4100 } else {
4101 if (!TryConsumeToken(tok::kw_auto)) {
4102 // Something like `void foo(Iterator decltype(int) i)`
4103 Tracker.skipToEnd();
4104 Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
4106 Tok.getLocation()),
4107 "auto");
4108 } else {
4109 Tracker.consumeClose();
4110 }
4111 }
4112 ConsumedEnd = Tok.getLocation();
4113 DS.setTypeArgumentRange(Tracker.getRange());
4114 // Even if something went wrong above, continue as if we've seen
4115 // `decltype(auto)`.
4117 DiagID, TemplateId, Policy);
4118 } else {
4119 isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
4120 TemplateId, Policy);
4121 }
4122 break;
4123 }
4124
4125 if (TemplateId->Kind != TNK_Type_template &&
4126 TemplateId->Kind != TNK_Undeclared_template) {
4127 // This template-id does not refer to a type name, so we're
4128 // done with the type-specifiers.
4129 goto DoneWithDeclSpec;
4130 }
4131
4132 // If we're in a context where the template-id could be a
4133 // constructor name or specialization, check whether this is a
4134 // constructor declaration.
4135 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
4136 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
4137 isConstructorDeclarator(/*Unqualified=*/true,
4138 /*DeductionGuide=*/false,
4139 DS.isFriendSpecified()))
4140 goto DoneWithDeclSpec;
4141
4142 // Turn the template-id annotation token into a type annotation
4143 // token, then try again to parse it as a type-specifier.
4144 CXXScopeSpec SS;
4145 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
4146 continue;
4147 }
4148
4149 // Attributes support.
4150 case tok::kw___attribute:
4151 case tok::kw___declspec:
4152 ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), LateAttrs);
4153 continue;
4154
4155 // Microsoft single token adornments.
4156 case tok::kw___forceinline: {
4157 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
4158 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
4159 SourceLocation AttrNameLoc = Tok.getLocation();
4160 DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
4161 nullptr, 0, tok::kw___forceinline);
4162 break;
4163 }
4164
4165 case tok::kw___unaligned:
4166 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
4167 getLangOpts());
4168 break;
4169
4170 case tok::kw___sptr:
4171 case tok::kw___uptr:
4172 case tok::kw___ptr64:
4173 case tok::kw___ptr32:
4174 case tok::kw___w64:
4175 case tok::kw___cdecl:
4176 case tok::kw___stdcall:
4177 case tok::kw___fastcall:
4178 case tok::kw___thiscall:
4179 case tok::kw___regcall:
4180 case tok::kw___vectorcall:
4181 ParseMicrosoftTypeAttributes(DS.getAttributes());
4182 continue;
4183
4184 case tok::kw___funcref:
4185 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
4186 continue;
4187
4188 // Borland single token adornments.
4189 case tok::kw___pascal:
4190 ParseBorlandTypeAttributes(DS.getAttributes());
4191 continue;
4192
4193 // OpenCL single token adornments.
4194 case tok::kw___kernel:
4195 ParseOpenCLKernelAttributes(DS.getAttributes());
4196 continue;
4197
4198 // CUDA/HIP single token adornments.
4199 case tok::kw___noinline__:
4200 ParseCUDAFunctionAttributes(DS.getAttributes());
4201 continue;
4202
4203 // Nullability type specifiers.
4204 case tok::kw__Nonnull:
4205 case tok::kw__Nullable:
4206 case tok::kw__Nullable_result:
4207 case tok::kw__Null_unspecified:
4208 ParseNullabilityTypeSpecifiers(DS.getAttributes());
4209 continue;
4210
4211 // Objective-C 'kindof' types.
4212 case tok::kw___kindof:
4213 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
4214 nullptr, 0, tok::kw___kindof);
4215 (void)ConsumeToken();
4216 continue;
4217
4218 // storage-class-specifier
4219 case tok::kw_typedef:
4221 PrevSpec, DiagID, Policy);
4222 isStorageClass = true;
4223 break;
4224 case tok::kw_extern:
4226 Diag(Tok, diag::ext_thread_before) << "extern";
4228 PrevSpec, DiagID, Policy);
4229 isStorageClass = true;
4230 break;
4231 case tok::kw___private_extern__:
4233 Loc, PrevSpec, DiagID, Policy);
4234 isStorageClass = true;
4235 break;
4236 case tok::kw_static:
4238 Diag(Tok, diag::ext_thread_before) << "static";
4240 PrevSpec, DiagID, Policy);
4241 isStorageClass = true;
4242 break;
4243 case tok::kw_auto:
4244 if (getLangOpts().CPlusPlus11 || getLangOpts().C23) {
4245 if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
4247 PrevSpec, DiagID, Policy);
4248 if (!isInvalid && !getLangOpts().C23)
4249 Diag(Tok, diag::ext_auto_storage_class)
4251 } else
4253 DiagID, Policy);
4254 } else
4256 PrevSpec, DiagID, Policy);
4257 isStorageClass = true;
4258 break;
4259 case tok::kw___auto_type:
4260 Diag(Tok, diag::ext_auto_type);
4262 DiagID, Policy);
4263 break;
4264 case tok::kw_register:
4266 PrevSpec, DiagID, Policy);
4267 isStorageClass = true;
4268 break;
4269 case tok::kw_mutable:
4271 PrevSpec, DiagID, Policy);
4272 isStorageClass = true;
4273 break;
4274 case tok::kw___thread:
4276 PrevSpec, DiagID);
4277 isStorageClass = true;
4278 break;
4279 case tok::kw_thread_local:
4280 if (getLangOpts().C23)
4281 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4282 // We map thread_local to _Thread_local in C23 mode so it retains the C
4283 // semantics rather than getting the C++ semantics.
4284 // FIXME: diagnostics will show _Thread_local when the user wrote
4285 // thread_local in source in C23 mode; we need some general way to
4286 // identify which way the user spelled the keyword in source.
4290 Loc, PrevSpec, DiagID);
4291 isStorageClass = true;
4292 break;
4293 case tok::kw__Thread_local:
4294 diagnoseUseOfC11Keyword(Tok);
4296 Loc, PrevSpec, DiagID);
4297 isStorageClass = true;
4298 break;
4299
4300 // function-specifier
4301 case tok::kw_inline:
4302 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
4303 break;
4304 case tok::kw_virtual:
4305 // C++ for OpenCL does not allow virtual function qualifier, to avoid
4306 // function pointers restricted in OpenCL v2.0 s6.9.a.
4307 if (getLangOpts().OpenCLCPlusPlus &&
4308 !getActions().getOpenCLOptions().isAvailableOption(
4309 "__cl_clang_function_pointers", getLangOpts())) {
4310 DiagID = diag::err_openclcxx_virtual_function;
4311 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4312 isInvalid = true;
4313 } else {
4314 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
4315 }
4316 break;
4317 case tok::kw_explicit: {
4318 SourceLocation ExplicitLoc = Loc;
4319 SourceLocation CloseParenLoc;
4321 ConsumedEnd = ExplicitLoc;
4322 ConsumeToken(); // kw_explicit
4323 if (Tok.is(tok::l_paren)) {
4324 if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
4326 ? diag::warn_cxx17_compat_explicit_bool
4327 : diag::ext_explicit_bool);
4328
4329 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
4330 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4331 Tracker.consumeOpen();
4332
4333 EnterExpressionEvaluationContext ConstantEvaluated(
4335
4337 ConsumedEnd = Tok.getLocation();
4338 if (ExplicitExpr.isUsable()) {
4339 CloseParenLoc = Tok.getLocation();
4340 Tracker.consumeClose();
4341 ExplicitSpec =
4342 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
4343 } else
4344 Tracker.skipToEnd();
4345 } else {
4346 Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
4347 }
4348 }
4349 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
4350 ExplicitSpec, CloseParenLoc);
4351 break;
4352 }
4353 case tok::kw__Noreturn:
4354 diagnoseUseOfC11Keyword(Tok);
4355 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
4356 break;
4357
4358 // friend
4359 case tok::kw_friend:
4360 if (DSContext == DeclSpecContext::DSC_class) {
4361 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
4362 Scope *CurS = getCurScope();
4363 if (!isInvalid && CurS)
4364 CurS->setFlags(CurS->getFlags() | Scope::FriendScope);
4365 } else {
4366 PrevSpec = ""; // not actually used by the diagnostic
4367 DiagID = diag::err_friend_invalid_in_context;
4368 isInvalid = true;
4369 }
4370 break;
4371
4372 // Modules
4373 case tok::kw___module_private__:
4374 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
4375 break;
4376
4377 // constexpr, consteval, constinit specifiers
4378 case tok::kw_constexpr:
4379 if (getLangOpts().C23)
4380 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4382 PrevSpec, DiagID);
4383 break;
4384 case tok::kw_consteval:
4386 PrevSpec, DiagID);
4387 break;
4388 case tok::kw_constinit:
4390 PrevSpec, DiagID);
4391 break;
4392
4393 // type-specifier
4394 case tok::kw_short:
4396 DiagID, Policy);
4397 break;
4398 case tok::kw_long:
4401 DiagID, Policy);
4402 else
4404 PrevSpec, DiagID, Policy);
4405 break;
4406 case tok::kw___int64:
4408 PrevSpec, DiagID, Policy);
4409 break;
4410 case tok::kw_signed:
4411 isInvalid =
4412 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4413 break;
4414 case tok::kw_unsigned:
4416 DiagID);
4417 break;
4418 case tok::kw__Complex:
4419 if (!getLangOpts().C99)
4420 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4422 DiagID);
4423 break;
4424 case tok::kw__Imaginary:
4425 if (!getLangOpts().C99)
4426 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4428 DiagID);
4429 break;
4430 case tok::kw_void:
4432 DiagID, Policy);
4433 break;
4434 case tok::kw_char:
4436 DiagID, Policy);
4437 break;
4438 case tok::kw_int:
4440 DiagID, Policy);
4441 break;
4442 case tok::kw__ExtInt:
4443 case tok::kw__BitInt: {
4444 DiagnoseBitIntUse(Tok);
4445 ExprResult ER = ParseExtIntegerArgument();
4446 if (ER.isInvalid())
4447 continue;
4448 isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
4449 ConsumedEnd = PrevTokLocation;
4450 break;
4451 }
4452 case tok::kw___int128:
4454 DiagID, Policy);
4455 break;
4456 case tok::kw_half:
4458 DiagID, Policy);
4459 break;
4460 case tok::kw___bf16:
4462 DiagID, Policy);
4463 break;
4464 case tok::kw_float:
4466 DiagID, Policy);
4467 break;
4468 case tok::kw_double:
4470 DiagID, Policy);
4471 break;
4472 case tok::kw__Float16:
4474 DiagID, Policy);
4475 break;
4476 case tok::kw__Accum:
4477 assert(getLangOpts().FixedPoint &&
4478 "This keyword is only used when fixed point types are enabled "
4479 "with `-ffixed-point`");
4480 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec, DiagID,
4481 Policy);
4482 break;
4483 case tok::kw__Fract:
4484 assert(getLangOpts().FixedPoint &&
4485 "This keyword is only used when fixed point types are enabled "
4486 "with `-ffixed-point`");
4487 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec, DiagID,
4488 Policy);
4489 break;
4490 case tok::kw__Sat:
4491 assert(getLangOpts().FixedPoint &&
4492 "This keyword is only used when fixed point types are enabled "
4493 "with `-ffixed-point`");
4494 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
4495 break;
4496 case tok::kw___float128:
4498 DiagID, Policy);
4499 break;
4500 case tok::kw___ibm128:
4502 DiagID, Policy);
4503 break;
4504 case tok::kw_wchar_t:
4506 DiagID, Policy);
4507 break;
4508 case tok::kw_char8_t:
4510 DiagID, Policy);
4511 break;
4512 case tok::kw_char16_t:
4514 DiagID, Policy);
4515 break;
4516 case tok::kw_char32_t:
4518 DiagID, Policy);
4519 break;
4520 case tok::kw_bool:
4521 if (getLangOpts().C23)
4522 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4523 [[fallthrough]];
4524 case tok::kw__Bool:
4525 if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
4526 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4527
4528 if (Tok.is(tok::kw_bool) &&
4531 PrevSpec = ""; // Not used by the diagnostic.
4532 DiagID = diag::err_bool_redeclaration;
4533 // For better error recovery.
4534 Tok.setKind(tok::identifier);
4535 isInvalid = true;
4536 } else {
4538 DiagID, Policy);
4539 }
4540 break;
4541 case tok::kw__Decimal32:
4543 DiagID, Policy);
4544 break;
4545 case tok::kw__Decimal64:
4547 DiagID, Policy);
4548 break;
4549 case tok::kw__Decimal128:
4551 DiagID, Policy);
4552 break;
4553 case tok::kw___vector:
4554 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4555 break;
4556 case tok::kw___pixel:
4557 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4558 break;
4559 case tok::kw___bool:
4560 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4561 break;
4562 case tok::kw_pipe:
4563 if (!getLangOpts().OpenCL ||
4564 getLangOpts().getOpenCLCompatibleVersion() < 200) {
4565 // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4566 // should support the "pipe" word as identifier.
4568 Tok.setKind(tok::identifier);
4569 goto DoneWithDeclSpec;
4570 } else if (!getLangOpts().OpenCLPipes) {
4571 DiagID = diag::err_opencl_unknown_type_specifier;
4572 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4573 isInvalid = true;
4574 } else
4575 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4576 break;
4577// We only need to enumerate each image type once.
4578#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4579#define IMAGE_WRITE_TYPE(Type, Id, Ext)
4580#define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4581 case tok::kw_##ImgType##_t: \
4582 if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4583 goto DoneWithDeclSpec; \
4584 break;
4585#include "clang/Basic/OpenCLImageTypes.def"
4586 case tok::kw___unknown_anytype:
4588 PrevSpec, DiagID, Policy);
4589 break;
4590
4591 // class-specifier:
4592 case tok::kw_class:
4593 case tok::kw_struct:
4594 case tok::kw___interface:
4595 case tok::kw_union: {
4596 tok::TokenKind Kind = Tok.getKind();
4597 ConsumeToken();
4598
4599 // These are attributes following class specifiers.
4600 // To produce better diagnostic, we parse them when
4601 // parsing class specifier.
4602 ParsedAttributes Attributes(AttrFactory);
4603 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4604 EnteringContext, DSContext, Attributes);
4605
4606 // If there are attributes following class specifier,
4607 // take them over and handle them here.
4608 if (!Attributes.empty()) {
4609 AttrsLastTime = true;
4610 attrs.takeAllFrom(Attributes);
4611 }
4612 continue;
4613 }
4614
4615 // enum-specifier:
4616 case tok::kw_enum:
4617 ConsumeToken();
4618 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4619 continue;
4620
4621 // cv-qualifier:
4622 case tok::kw_const:
4623 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4624 getLangOpts());
4625 break;
4626 case tok::kw_volatile:
4627 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4628 getLangOpts());
4629 break;
4630 case tok::kw_restrict:
4631 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4632 getLangOpts());
4633 break;
4634
4635 // C++ typename-specifier:
4636 case tok::kw_typename:
4638 DS.SetTypeSpecError();
4639 goto DoneWithDeclSpec;
4640 }
4641 if (!Tok.is(tok::kw_typename))
4642 continue;
4643 break;
4644
4645 // C23/GNU typeof support.
4646 case tok::kw_typeof:
4647 case tok::kw_typeof_unqual:
4648 ParseTypeofSpecifier(DS);
4649 continue;
4650
4651 case tok::annot_decltype:
4652 ParseDecltypeSpecifier(DS);
4653 continue;
4654
4655 case tok::annot_pack_indexing_type:
4656 ParsePackIndexingType(DS);
4657 continue;
4658
4659 case tok::annot_pragma_pack:
4660 HandlePragmaPack();
4661 continue;
4662
4663 case tok::annot_pragma_ms_pragma:
4664 HandlePragmaMSPragma();
4665 continue;
4666
4667 case tok::annot_pragma_ms_vtordisp:
4668 HandlePragmaMSVtorDisp();
4669 continue;
4670
4671 case tok::annot_pragma_ms_pointers_to_members:
4672 HandlePragmaMSPointersToMembers();
4673 continue;
4674
4675#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
4676#include "clang/Basic/TransformTypeTraits.def"
4677 // HACK: libstdc++ already uses '__remove_cv' as an alias template so we
4678 // work around this by expecting all transform type traits to be suffixed
4679 // with '('. They're an identifier otherwise.
4680 if (!MaybeParseTypeTransformTypeSpecifier(DS))
4681 goto ParseIdentifier;
4682 continue;
4683
4684 case tok::kw__Atomic:
4685 // C11 6.7.2.4/4:
4686 // If the _Atomic keyword is immediately followed by a left parenthesis,
4687 // it is interpreted as a type specifier (with a type name), not as a
4688 // type qualifier.
4689 diagnoseUseOfC11Keyword(Tok);
4690 if (NextToken().is(tok::l_paren)) {
4691 ParseAtomicSpecifier(DS);
4692 continue;
4693 }
4694 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4695 getLangOpts());
4696 break;
4697
4698 // OpenCL address space qualifiers:
4699 case tok::kw___generic:
4700 // generic address space is introduced only in OpenCL v2.0
4701 // see OpenCL C Spec v2.0 s6.5.5
4702 // OpenCL v3.0 introduces __opencl_c_generic_address_space
4703 // feature macro to indicate if generic address space is supported
4704 if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4705 DiagID = diag::err_opencl_unknown_type_specifier;
4706 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4707 isInvalid = true;
4708 break;
4709 }
4710 [[fallthrough]];
4711 case tok::kw_private:
4712 // It's fine (but redundant) to check this for __generic on the
4713 // fallthrough path; we only form the __generic token in OpenCL mode.
4714 if (!getLangOpts().OpenCL)
4715 goto DoneWithDeclSpec;
4716 [[fallthrough]];
4717 case tok::kw___private:
4718 case tok::kw___global:
4719 case tok::kw___local:
4720 case tok::kw___constant:
4721 // OpenCL access qualifiers:
4722 case tok::kw___read_only:
4723 case tok::kw___write_only:
4724 case tok::kw___read_write:
4725 ParseOpenCLQualifiers(DS.getAttributes());
4726 break;
4727
4728 case tok::kw_groupshared:
4729 case tok::kw_in:
4730 case tok::kw_inout:
4731 case tok::kw_out:
4732 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4733 ParseHLSLQualifiers(DS.getAttributes());
4734 continue;
4735
4736 case tok::less:
4737 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4738 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4739 // but we support it.
4740 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4741 goto DoneWithDeclSpec;
4742
4743 SourceLocation StartLoc = Tok.getLocation();
4744 SourceLocation EndLoc;
4745 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4746 if (Type.isUsable()) {
4747 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4748 PrevSpec, DiagID, Type.get(),
4749 Actions.getASTContext().getPrintingPolicy()))
4750 Diag(StartLoc, DiagID) << PrevSpec;
4751
4752 DS.SetRangeEnd(EndLoc);
4753 } else {
4754 DS.SetTypeSpecError();
4755 }
4756
4757 // Need to support trailing type qualifiers (e.g. "id<p> const").
4758 // If a type specifier follows, it will be diagnosed elsewhere.
4759 continue;
4760 }
4761
4762 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4763
4764 // If the specifier wasn't legal, issue a diagnostic.
4765 if (isInvalid) {
4766 assert(PrevSpec && "Method did not return previous specifier!");
4767 assert(DiagID);
4768
4769 if (DiagID == diag::ext_duplicate_declspec ||
4770 DiagID == diag::ext_warn_duplicate_declspec ||
4771 DiagID == diag::err_duplicate_declspec)
4772 Diag(Loc, DiagID) << PrevSpec
4774 SourceRange(Loc, DS.getEndLoc()));
4775 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4776 Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4777 << isStorageClass;
4778 } else
4779 Diag(Loc, DiagID) << PrevSpec;
4780 }
4781
4782 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4783 // After an error the next token can be an annotation token.
4785
4786 AttrsLastTime = false;
4787 }
4788}
4789
4791 Parser &P) {
4792
4794 return;
4795
4796 auto *RD = dyn_cast<RecordDecl>(DS.getRepAsDecl());
4797 // We're only interested in unnamed, non-anonymous struct
4798 if (!RD || !RD->getName().empty() || RD->isAnonymousStructOrUnion())
4799 return;
4800
4801 for (auto *I : RD->decls()) {
4802 auto *VD = dyn_cast<ValueDecl>(I);
4803 if (!VD)
4804 continue;
4805
4806 auto *CAT = VD->getType()->getAs<CountAttributedType>();
4807 if (!CAT)
4808 continue;
4809
4810 for (const auto &DD : CAT->dependent_decls()) {
4811 if (!RD->containsDecl(DD.getDecl())) {
4812 P.Diag(VD->getBeginLoc(),
4813 diag::err_flexible_array_count_not_in_same_struct)
4814 << DD.getDecl();
4815 P.Diag(DD.getDecl()->getBeginLoc(),
4816 diag::note_flexible_array_counted_by_attr_field)
4817 << DD.getDecl();
4818 }
4819 }
4820 }
4821}
4822
4823/// ParseStructDeclaration - Parse a struct declaration without the terminating
4824/// semicolon.
4825///
4826/// Note that a struct declaration refers to a declaration in a struct,
4827/// not to the declaration of a struct.
4828///
4829/// struct-declaration:
4830/// [C23] attributes-specifier-seq[opt]
4831/// specifier-qualifier-list struct-declarator-list
4832/// [GNU] __extension__ struct-declaration
4833/// [GNU] specifier-qualifier-list
4834/// struct-declarator-list:
4835/// struct-declarator
4836/// struct-declarator-list ',' struct-declarator
4837/// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4838/// struct-declarator:
4839/// declarator
4840/// [GNU] declarator attributes[opt]
4841/// declarator[opt] ':' constant-expression
4842/// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4843///
4844void Parser::ParseStructDeclaration(
4845 ParsingDeclSpec &DS,
4846 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4847
4848 if (Tok.is(tok::kw___extension__)) {
4849 // __extension__ silences extension warnings in the subexpression.
4850 ExtensionRAIIObject O(Diags); // Use RAII to do this.
4851 ConsumeToken();
4852 return ParseStructDeclaration(DS, FieldsCallback);
4853 }
4854
4855 // Parse leading attributes.
4856 ParsedAttributes Attrs(AttrFactory);
4857 MaybeParseCXX11Attributes(Attrs);
4858
4859 // Parse the common specifier-qualifiers-list piece.
4860 ParseSpecifierQualifierList(DS);
4861
4862 // If there are no declarators, this is a free-standing declaration
4863 // specifier. Let the actions module cope with it.
4864 if (Tok.is(tok::semi)) {
4865 // C23 6.7.2.1p9 : "The optional attribute specifier sequence in a
4866 // member declaration appertains to each of the members declared by the
4867 // member declarator list; it shall not appear if the optional member
4868 // declarator list is omitted."
4869 ProhibitAttributes(Attrs);
4870 RecordDecl *AnonRecord = nullptr;
4871 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
4872 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
4873 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4874 DS.complete(TheDecl);
4875 return;
4876 }
4877
4878 // Read struct-declarators until we find the semicolon.
4879 bool FirstDeclarator = true;
4880 SourceLocation CommaLoc;
4881 while (true) {
4882 ParsingFieldDeclarator DeclaratorInfo(*this, DS, Attrs);
4883 DeclaratorInfo.D.setCommaLoc(CommaLoc);
4884
4885 // Attributes are only allowed here on successive declarators.
4886 if (!FirstDeclarator) {
4887 // However, this does not apply for [[]] attributes (which could show up
4888 // before or after the __attribute__ attributes).
4889 DiagnoseAndSkipCXX11Attributes();
4890 MaybeParseGNUAttributes(DeclaratorInfo.D);
4891 DiagnoseAndSkipCXX11Attributes();
4892 }
4893
4894 /// struct-declarator: declarator
4895 /// struct-declarator: declarator[opt] ':' constant-expression
4896 if (Tok.isNot(tok::colon)) {
4897 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4899 ParseDeclarator(DeclaratorInfo.D);
4900 } else
4901 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4902
4903 // Here, we now know that the unnamed struct is not an anonymous struct.
4904 // Report an error if a counted_by attribute refers to a field in a
4905 // different named struct.
4907
4908 if (TryConsumeToken(tok::colon)) {
4910 if (Res.isInvalid())
4911 SkipUntil(tok::semi, StopBeforeMatch);
4912 else
4913 DeclaratorInfo.BitfieldSize = Res.get();
4914 }
4915
4916 // If attributes exist after the declarator, parse them.
4917 MaybeParseGNUAttributes(DeclaratorInfo.D);
4918
4919 // We're done with this declarator; invoke the callback.
4920 FieldsCallback(DeclaratorInfo);
4921
4922 // If we don't have a comma, it is either the end of the list (a ';')
4923 // or an error, bail out.
4924 if (!TryConsumeToken(tok::comma, CommaLoc))
4925 return;
4926
4927 FirstDeclarator = false;
4928 }
4929}
4930
4931/// ParseStructUnionBody
4932/// struct-contents:
4933/// struct-declaration-list
4934/// [EXT] empty
4935/// [GNU] "struct-declaration-list" without terminating ';'
4936/// struct-declaration-list:
4937/// struct-declaration
4938/// struct-declaration-list struct-declaration
4939/// [OBC] '@' 'defs' '(' class-name ')'
4940///
4941void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4944 "parsing struct/union body");
4945 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4946
4947 BalancedDelimiterTracker T(*this, tok::l_brace);
4948 if (T.consumeOpen())
4949 return;
4950
4951 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4953
4954 // While we still have something to read, read the declarations in the struct.
4955 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4956 Tok.isNot(tok::eof)) {
4957 // Each iteration of this loop reads one struct-declaration.
4958
4959 // Check for extraneous top-level semicolon.
4960 if (Tok.is(tok::semi)) {
4961 ConsumeExtraSemi(InsideStruct, TagType);
4962 continue;
4963 }
4964
4965 // Parse _Static_assert declaration.
4966 if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
4967 SourceLocation DeclEnd;
4968 ParseStaticAssertDeclaration(DeclEnd);
4969 continue;
4970 }
4971
4972 if (Tok.is(tok::annot_pragma_pack)) {
4973 HandlePragmaPack();
4974 continue;
4975 }
4976
4977 if (Tok.is(tok::annot_pragma_align)) {
4978 HandlePragmaAlign();
4979 continue;
4980 }
4981
4982 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
4983 // Result can be ignored, because it must be always empty.
4985 ParsedAttributes Attrs(AttrFactory);
4986 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4987 continue;
4988 }
4989
4990 if (Tok.is(tok::annot_pragma_openacc)) {
4992 continue;
4993 }
4994
4995 if (tok::isPragmaAnnotation(Tok.getKind())) {
4996 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4999 ConsumeAnnotationToken();
5000 continue;
5001 }
5002
5003 if (!Tok.is(tok::at)) {
5004 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
5005 // Install the declarator into the current TagDecl.
5006 Decl *Field =
5007 Actions.ActOnField(getCurScope(), TagDecl,
5008 FD.D.getDeclSpec().getSourceRange().getBegin(),
5009 FD.D, FD.BitfieldSize);
5010 FD.complete(Field);
5011 };
5012
5013 // Parse all the comma separated declarators.
5014 ParsingDeclSpec DS(*this);
5015 ParseStructDeclaration(DS, CFieldCallback);
5016 } else { // Handle @defs
5017 ConsumeToken();
5018 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
5019 Diag(Tok, diag::err_unexpected_at);
5020 SkipUntil(tok::semi);
5021 continue;
5022 }
5023 ConsumeToken();
5024 ExpectAndConsume(tok::l_paren);
5025 if (!Tok.is(tok::identifier)) {
5026 Diag(Tok, diag::err_expected) << tok::identifier;
5027 SkipUntil(tok::semi);
5028 continue;
5029 }
5031 Actions.ObjC().ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
5032 Tok.getIdentifierInfo(), Fields);
5033 ConsumeToken();
5034 ExpectAndConsume(tok::r_paren);
5035 }
5036
5037 if (TryConsumeToken(tok::semi))
5038 continue;
5039
5040 if (Tok.is(tok::r_brace)) {
5041 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
5042 break;
5043 }
5044
5045 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
5046 // Skip to end of block or statement to avoid ext-warning on extra ';'.
5047 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
5048 // If we stopped at a ';', eat it.
5049 TryConsumeToken(tok::semi);
5050 }
5051
5052 T.consumeClose();
5053
5054 ParsedAttributes attrs(AttrFactory);
5055 // If attributes exist after struct contents, parse them.
5056 MaybeParseGNUAttributes(attrs);
5057
5058 SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
5059
5060 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
5061 T.getOpenLocation(), T.getCloseLocation(), attrs);
5062 StructScope.Exit();
5063 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
5064}
5065
5066/// ParseEnumSpecifier
5067/// enum-specifier: [C99 6.7.2.2]
5068/// 'enum' identifier[opt] '{' enumerator-list '}'
5069///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
5070/// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
5071/// '}' attributes[opt]
5072/// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
5073/// '}'
5074/// 'enum' identifier
5075/// [GNU] 'enum' attributes[opt] identifier
5076///
5077/// [C++11] enum-head '{' enumerator-list[opt] '}'
5078/// [C++11] enum-head '{' enumerator-list ',' '}'
5079///
5080/// enum-head: [C++11]
5081/// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
5082/// enum-key attribute-specifier-seq[opt] nested-name-specifier
5083/// identifier enum-base[opt]
5084///
5085/// enum-key: [C++11]
5086/// 'enum'
5087/// 'enum' 'class'
5088/// 'enum' 'struct'
5089///
5090/// enum-base: [C++11]
5091/// ':' type-specifier-seq
5092///
5093/// [C++] elaborated-type-specifier:
5094/// [C++] 'enum' nested-name-specifier[opt] identifier
5095///
5096void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
5097 const ParsedTemplateInfo &TemplateInfo,
5098 AccessSpecifier AS, DeclSpecContext DSC) {
5099 // Parse the tag portion of this.
5100 if (Tok.is(tok::code_completion)) {
5101 // Code completion for an enum name.
5102 cutOffParsing();
5104 DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
5105 return;
5106 }
5107
5108 // If attributes exist after tag, parse them.
5109 ParsedAttributes attrs(AttrFactory);
5110 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
5111
5112 SourceLocation ScopedEnumKWLoc;
5113 bool IsScopedUsingClassTag = false;
5114
5115 // In C++11, recognize 'enum class' and 'enum struct'.
5116 if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
5117 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
5118 : diag::ext_scoped_enum);
5119 IsScopedUsingClassTag = Tok.is(tok::kw_class);
5120 ScopedEnumKWLoc = ConsumeToken();
5121
5122 // Attributes are not allowed between these keywords. Diagnose,
5123 // but then just treat them like they appeared in the right place.
5124 ProhibitAttributes(attrs);
5125
5126 // They are allowed afterwards, though.
5127 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
5128 }
5129
5130 // C++11 [temp.explicit]p12:
5131 // The usual access controls do not apply to names used to specify
5132 // explicit instantiations.
5133 // We extend this to also cover explicit specializations. Note that
5134 // we don't suppress if this turns out to be an elaborated type
5135 // specifier.
5136 bool shouldDelayDiagsInTag =
5137 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
5138 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
5139 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
5140
5141 // Determine whether this declaration is permitted to have an enum-base.
5142 AllowDefiningTypeSpec AllowEnumSpecifier =
5143 isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus);
5144 bool CanBeOpaqueEnumDeclaration =
5145 DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
5146 bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
5147 getLangOpts().MicrosoftExt) &&
5148 (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
5149 CanBeOpaqueEnumDeclaration);
5150
5151 CXXScopeSpec &SS = DS.getTypeSpecScope();
5152 if (getLangOpts().CPlusPlus) {
5153 // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
5155
5156 CXXScopeSpec Spec;
5157 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
5158 /*ObjectHasErrors=*/false,
5159 /*EnteringContext=*/true))
5160 return;
5161
5162 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
5163 Diag(Tok, diag::err_expected) << tok::identifier;
5164 DS.SetTypeSpecError();
5165 if (Tok.isNot(tok::l_brace)) {
5166 // Has no name and is not a definition.
5167 // Skip the rest of this declarator, up until the comma or semicolon.
5168 SkipUntil(tok::comma, StopAtSemi);
5169 return;
5170 }
5171 }
5172
5173 SS = Spec;
5174 }
5175
5176 // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
5177 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
5178 Tok.isNot(tok::colon)) {
5179 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
5180
5181 DS.SetTypeSpecError();
5182 // Skip the rest of this declarator, up until the comma or semicolon.
5183 SkipUntil(tok::comma, StopAtSemi);
5184 return;
5185 }
5186
5187 // If an identifier is present, consume and remember it.
5188 IdentifierInfo *Name = nullptr;
5189 SourceLocation NameLoc;
5190 if (Tok.is(tok::identifier)) {
5191 Name = Tok.getIdentifierInfo();
5192 NameLoc = ConsumeToken();
5193 }
5194
5195 if (!Name && ScopedEnumKWLoc.isValid()) {
5196 // C++0x 7.2p2: The optional identifier shall not be omitted in the
5197 // declaration of a scoped enumeration.
5198 Diag(Tok, diag::err_scoped_enum_missing_identifier);
5199 ScopedEnumKWLoc = SourceLocation();
5200 IsScopedUsingClassTag = false;
5201 }
5202
5203 // Okay, end the suppression area. We'll decide whether to emit the
5204 // diagnostics in a second.
5205 if (shouldDelayDiagsInTag)
5206 diagsFromTag.done();
5207
5208 TypeResult BaseType;
5209 SourceRange BaseRange;
5210
5211 bool CanBeBitfield =
5212 getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
5213
5214 // Parse the fixed underlying type.
5215 if (Tok.is(tok::colon)) {
5216 // This might be an enum-base or part of some unrelated enclosing context.
5217 //
5218 // 'enum E : base' is permitted in two circumstances:
5219 //
5220 // 1) As a defining-type-specifier, when followed by '{'.
5221 // 2) As the sole constituent of a complete declaration -- when DS is empty
5222 // and the next token is ';'.
5223 //
5224 // The restriction to defining-type-specifiers is important to allow parsing
5225 // a ? new enum E : int{}
5226 // _Generic(a, enum E : int{})
5227 // properly.
5228 //
5229 // One additional consideration applies:
5230 //
5231 // C++ [dcl.enum]p1:
5232 // A ':' following "enum nested-name-specifier[opt] identifier" within
5233 // the decl-specifier-seq of a member-declaration is parsed as part of
5234 // an enum-base.
5235 //
5236 // Other language modes supporting enumerations with fixed underlying types
5237 // do not have clear rules on this, so we disambiguate to determine whether
5238 // the tokens form a bit-field width or an enum-base.
5239
5240 if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
5241 // Outside C++11, do not interpret the tokens as an enum-base if they do
5242 // not make sense as one. In C++11, it's an error if this happens.
5244 Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
5245 } else if (CanHaveEnumBase || !ColonIsSacred) {
5246 SourceLocation ColonLoc = ConsumeToken();
5247
5248 // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
5249 // because under -fms-extensions,
5250 // enum E : int *p;
5251 // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
5252 DeclSpec DS(AttrFactory);
5253 // enum-base is not assumed to be a type and therefore requires the
5254 // typename keyword [p0634r3].
5255 ParseSpecifierQualifierList(DS, ImplicitTypenameContext::No, AS,
5256 DeclSpecContext::DSC_type_specifier);
5257 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
5259 BaseType = Actions.ActOnTypeName(DeclaratorInfo);
5260
5261 BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
5262
5263 if (!getLangOpts().ObjC && !getLangOpts().C23) {
5265 Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
5266 << BaseRange;
5267 else if (getLangOpts().CPlusPlus)
5268 Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
5269 << BaseRange;
5270 else if (getLangOpts().MicrosoftExt)
5271 Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
5272 << BaseRange;
5273 else
5274 Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
5275 << BaseRange;
5276 }
5277 }
5278 }
5279
5280 // There are four options here. If we have 'friend enum foo;' then this is a
5281 // friend declaration, and cannot have an accompanying definition. If we have
5282 // 'enum foo;', then this is a forward declaration. If we have
5283 // 'enum foo {...' then this is a definition. Otherwise we have something
5284 // like 'enum foo xyz', a reference.
5285 //
5286 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
5287 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
5288 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
5289 //
5290 Sema::TagUseKind TUK;
5291 if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
5292 TUK = Sema::TUK_Reference;
5293 else if (Tok.is(tok::l_brace)) {
5294 if (DS.isFriendSpecified()) {
5295 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
5297 ConsumeBrace();
5298 SkipUntil(tok::r_brace, StopAtSemi);
5299 // Discard any other definition-only pieces.
5300 attrs.clear();
5301 ScopedEnumKWLoc = SourceLocation();
5302 IsScopedUsingClassTag = false;
5303 BaseType = TypeResult();
5304 TUK = Sema::TUK_Friend;
5305 } else {
5307 }
5308 } else if (!isTypeSpecifier(DSC) &&
5309 (Tok.is(tok::semi) ||
5310 (Tok.isAtStartOfLine() &&
5311 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
5312 // An opaque-enum-declaration is required to be standalone (no preceding or
5313 // following tokens in the declaration). Sema enforces this separately by
5314 // diagnosing anything else in the DeclSpec.
5316 if (Tok.isNot(tok::semi)) {
5317 // A semicolon was missing after this declaration. Diagnose and recover.
5318 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5319 PP.EnterToken(Tok, /*IsReinject=*/true);
5320 Tok.setKind(tok::semi);
5321 }
5322 } else {
5323 TUK = Sema::TUK_Reference;
5324 }
5325
5326 bool IsElaboratedTypeSpecifier =
5327 TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend;
5328
5329 // If this is an elaborated type specifier nested in a larger declaration,
5330 // and we delayed diagnostics before, just merge them into the current pool.
5331 if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
5332 diagsFromTag.redelay();
5333 }
5334
5335 MultiTemplateParamsArg TParams;
5336 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
5337 TUK != Sema::TUK_Reference) {
5338 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
5339 // Skip the rest of this declarator, up until the comma or semicolon.
5340 Diag(Tok, diag::err_enum_template);
5341 SkipUntil(tok::comma, StopAtSemi);
5342 return;
5343 }
5344
5345 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
5346 // Enumerations can't be explicitly instantiated.
5347 DS.SetTypeSpecError();
5348 Diag(StartLoc, diag::err_explicit_instantiation_enum);
5349 return;
5350 }
5351
5352 assert(TemplateInfo.TemplateParams && "no template parameters");
5353 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
5354 TemplateInfo.TemplateParams->size());
5355 SS.setTemplateParamLists(TParams);
5356 }
5357
5358 if (!Name && TUK != Sema::TUK_Definition) {
5359 Diag(Tok, diag::err_enumerator_unnamed_no_def);
5360
5361 DS.SetTypeSpecError();
5362 // Skip the rest of this declarator, up until the comma or semicolon.
5363 SkipUntil(tok::comma, StopAtSemi);
5364 return;
5365 }
5366
5367 // An elaborated-type-specifier has a much more constrained grammar:
5368 //
5369 // 'enum' nested-name-specifier[opt] identifier
5370 //
5371 // If we parsed any other bits, reject them now.
5372 //
5373 // MSVC and (for now at least) Objective-C permit a full enum-specifier
5374 // or opaque-enum-declaration anywhere.
5375 if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
5376 !getLangOpts().ObjC) {
5377 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
5378 diag::err_keyword_not_allowed,
5379 /*DiagnoseEmptyAttrs=*/true);
5380 if (BaseType.isUsable())
5381 Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
5382 << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
5383 else if (ScopedEnumKWLoc.isValid())
5384 Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
5385 << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
5386 }
5387
5388 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
5389
5390 SkipBodyInfo SkipBody;
5391 if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
5392 NextToken().is(tok::identifier))
5393 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
5394 NextToken().getIdentifierInfo(),
5395 NextToken().getLocation());
5396
5397 bool Owned = false;
5398 bool IsDependent = false;
5399 const char *PrevSpec = nullptr;
5400 unsigned DiagID;
5401 Decl *TagDecl =
5402 Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS,
5403 Name, NameLoc, attrs, AS, DS.getModulePrivateSpecLoc(),
5404 TParams, Owned, IsDependent, ScopedEnumKWLoc,
5405 IsScopedUsingClassTag,
5406 BaseType, DSC == DeclSpecContext::DSC_type_specifier,
5407 DSC == DeclSpecContext::DSC_template_param ||
5408 DSC == DeclSpecContext::DSC_template_type_arg,
5409 OffsetOfState, &SkipBody).get();
5410
5411 if (SkipBody.ShouldSkip) {
5412 assert(TUK == Sema::TUK_Definition && "can only skip a definition");
5413
5414 BalancedDelimiterTracker T(*this, tok::l_brace);
5415 T.consumeOpen();
5416 T.skipToEnd();
5417
5418 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5419 NameLoc.isValid() ? NameLoc : StartLoc,
5420 PrevSpec, DiagID, TagDecl, Owned,
5421 Actions.getASTContext().getPrintingPolicy()))
5422 Diag(StartLoc, DiagID) << PrevSpec;
5423 return;
5424 }
5425
5426 if (IsDependent) {
5427 // This enum has a dependent nested-name-specifier. Handle it as a
5428 // dependent tag.
5429 if (!Name) {
5430 DS.SetTypeSpecError();
5431 Diag(Tok, diag::err_expected_type_name_after_typename);
5432 return;
5433 }
5434
5436 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
5437 if (Type.isInvalid()) {
5438 DS.SetTypeSpecError();
5439 return;
5440 }
5441
5442 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
5443 NameLoc.isValid() ? NameLoc : StartLoc,
5444 PrevSpec, DiagID, Type.get(),
5445 Actions.getASTContext().getPrintingPolicy()))
5446 Diag(StartLoc, DiagID) << PrevSpec;
5447
5448 return;
5449 }
5450
5451 if (!TagDecl) {
5452 // The action failed to produce an enumeration tag. If this is a
5453 // definition, consume the entire definition.
5454 if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
5455 ConsumeBrace();
5456 SkipUntil(tok::r_brace, StopAtSemi);
5457 }
5458
5459 DS.SetTypeSpecError();
5460 return;
5461 }
5462
5463 if (Tok.is(tok::l_brace) && TUK == Sema::TUK_Definition) {
5464 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
5465 ParseEnumBody(StartLoc, D);
5466 if (SkipBody.CheckSameAsPrevious &&
5467 !Actions.ActOnDuplicateDefinition(TagDecl, SkipBody)) {
5468 DS.SetTypeSpecError();
5469 return;
5470 }
5471 }
5472
5473 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5474 NameLoc.isValid() ? NameLoc : StartLoc,
5475 PrevSpec, DiagID, TagDecl, Owned,
5476 Actions.getASTContext().getPrintingPolicy()))
5477 Diag(StartLoc, DiagID) << PrevSpec;
5478}
5479
5480/// ParseEnumBody - Parse a {} enclosed enumerator-list.
5481/// enumerator-list:
5482/// enumerator
5483/// enumerator-list ',' enumerator
5484/// enumerator:
5485/// enumeration-constant attributes[opt]
5486/// enumeration-constant attributes[opt] '=' constant-expression
5487/// enumeration-constant:
5488/// identifier
5489///
5490void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
5491 // Enter the scope of the enum body and start the definition.
5492 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
5494
5495 BalancedDelimiterTracker T(*this, tok::l_brace);
5496 T.consumeOpen();
5497
5498 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
5499 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
5500 Diag(Tok, diag::err_empty_enum);
5501
5502 SmallVector<Decl *, 32> EnumConstantDecls;
5503 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
5504
5505 Decl *LastEnumConstDecl = nullptr;
5506
5507 // Parse the enumerator-list.
5508 while (Tok.isNot(tok::r_brace)) {
5509 // Parse enumerator. If failed, try skipping till the start of the next
5510 // enumerator definition.
5511 if (Tok.isNot(tok::identifier)) {
5512 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
5513 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
5514 TryConsumeToken(tok::comma))
5515 continue;
5516 break;
5517 }
5518 IdentifierInfo *Ident = Tok.getIdentifierInfo();
5519 SourceLocation IdentLoc = ConsumeToken();
5520
5521 // If attributes exist after the enumerator, parse them.
5522 ParsedAttributes attrs(AttrFactory);
5523 MaybeParseGNUAttributes(attrs);
5524 if (isAllowedCXX11AttributeSpecifier()) {
5525 if (getLangOpts().CPlusPlus)
5527 ? diag::warn_cxx14_compat_ns_enum_attribute
5528 : diag::ext_ns_enum_attribute)
5529 << 1 /*enumerator*/;
5530 ParseCXX11Attributes(attrs);
5531 }
5532
5533 SourceLocation EqualLoc;
5534 ExprResult AssignedVal;
5535 EnumAvailabilityDiags.emplace_back(*this);
5536
5537 EnterExpressionEvaluationContext ConstantEvaluated(
5539 if (TryConsumeToken(tok::equal, EqualLoc)) {
5541 if (AssignedVal.isInvalid())
5542 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
5543 }
5544
5545 // Install the enumerator constant into EnumDecl.
5546 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
5547 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
5548 EqualLoc, AssignedVal.get());
5549 EnumAvailabilityDiags.back().done();
5550
5551 EnumConstantDecls.push_back(EnumConstDecl);
5552 LastEnumConstDecl = EnumConstDecl;
5553
5554 if (Tok.is(tok::identifier)) {
5555 // We're missing a comma between enumerators.
5557 Diag(Loc, diag::err_enumerator_list_missing_comma)
5559 continue;
5560 }
5561
5562 // Emumerator definition must be finished, only comma or r_brace are
5563 // allowed here.
5564 SourceLocation CommaLoc;
5565 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
5566 if (EqualLoc.isValid())
5567 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
5568 << tok::comma;
5569 else
5570 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
5571 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
5572 if (TryConsumeToken(tok::comma, CommaLoc))
5573 continue;
5574 } else {
5575 break;
5576 }
5577 }
5578
5579 // If comma is followed by r_brace, emit appropriate warning.
5580 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
5582 Diag(CommaLoc, getLangOpts().CPlusPlus ?
5583 diag::ext_enumerator_list_comma_cxx :
5584 diag::ext_enumerator_list_comma_c)
5585 << FixItHint::CreateRemoval(CommaLoc);
5586 else if (getLangOpts().CPlusPlus11)
5587 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
5588 << FixItHint::CreateRemoval(CommaLoc);
5589 break;
5590 }
5591 }
5592
5593 // Eat the }.
5594 T.consumeClose();
5595
5596 // If attributes exist after the identifier list, parse them.
5597 ParsedAttributes attrs(AttrFactory);
5598 MaybeParseGNUAttributes(attrs);
5599
5600 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
5601 getCurScope(), attrs);
5602
5603 // Now handle enum constant availability diagnostics.
5604 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
5605 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
5607 EnumAvailabilityDiags[i].redelay();
5608 PD.complete(EnumConstantDecls[i]);
5609 }
5610
5611 EnumScope.Exit();
5612 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
5613
5614 // The next token must be valid after an enum definition. If not, a ';'
5615 // was probably forgotten.
5616 bool CanBeBitfield = getCurScope()->isClassScope();
5617 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
5618 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5619 // Push this token back into the preprocessor and change our current token
5620 // to ';' so that the rest of the code recovers as though there were an
5621 // ';' after the definition.
5622 PP.EnterToken(Tok, /*IsReinject=*/true);
5623 Tok.setKind(tok::semi);
5624 }
5625}
5626
5627/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
5628/// is definitely a type-specifier. Return false if it isn't part of a type
5629/// specifier or if we're not sure.
5630bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
5631 switch (Tok.getKind()) {
5632 default: return false;
5633 // type-specifiers
5634 case tok::kw_short:
5635 case tok::kw_long:
5636 case tok::kw___int64:
5637 case tok::kw___int128:
5638 case tok::kw_signed:
5639 case tok::kw_unsigned:
5640 case tok::kw__Complex:
5641 case tok::kw__Imaginary:
5642 case tok::kw_void:
5643 case tok::kw_char:
5644 case tok::kw_wchar_t:
5645 case tok::kw_char8_t:
5646 case tok::kw_char16_t:
5647 case tok::kw_char32_t:
5648 case tok::kw_int:
5649 case tok::kw__ExtInt:
5650 case tok::kw__BitInt:
5651 case tok::kw___bf16:
5652 case tok::kw_half:
5653 case tok::kw_float:
5654 case tok::kw_double:
5655 case tok::kw__Accum:
5656 case tok::kw__Fract:
5657 case tok::kw__Float16:
5658 case tok::kw___float128:
5659 case tok::kw___ibm128:
5660 case tok::kw_bool:
5661 case tok::kw__Bool:
5662 case tok::kw__Decimal32:
5663 case tok::kw__Decimal64:
5664 case tok::kw__Decimal128:
5665 case tok::kw___vector:
5666#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5667#include "clang/Basic/OpenCLImageTypes.def"
5668
5669 // struct-or-union-specifier (C99) or class-specifier (C++)
5670 case tok::kw_class:
5671 case tok::kw_struct:
5672 case tok::kw___interface:
5673 case tok::kw_union:
5674 // enum-specifier
5675 case tok::kw_enum:
5676
5677 // typedef-name
5678 case tok::annot_typename:
5679 return true;
5680 }
5681}
5682
5683/// isTypeSpecifierQualifier - Return true if the current token could be the
5684/// start of a specifier-qualifier-list.
5685bool Parser::isTypeSpecifierQualifier() {
5686 switch (Tok.getKind()) {
5687 default: return false;
5688
5689 case tok::identifier: // foo::bar
5690 if (TryAltiVecVectorToken())
5691 return true;
5692 [[fallthrough]];
5693 case tok::kw_typename: // typename T::type
5694 // Annotate typenames and C++ scope specifiers. If we get one, just
5695 // recurse to handle whatever we get.
5697 return true;
5698 if (Tok.is(tok::identifier))
5699 return false;
5700 return isTypeSpecifierQualifier();
5701
5702 case tok::coloncolon: // ::foo::bar
5703 if (NextToken().is(tok::kw_new) || // ::new
5704 NextToken().is(tok::kw_delete)) // ::delete
5705 return false;
5706
5708 return true;
5709 return isTypeSpecifierQualifier();
5710
5711 // GNU attributes support.
5712 case tok::kw___attribute:
5713 // C23/GNU typeof support.
5714 case tok::kw_typeof:
5715 case tok::kw_typeof_unqual:
5716
5717 // type-specifiers
5718 case tok::kw_short:
5719 case tok::kw_long:
5720 case tok::kw___int64:
5721 case tok::kw___int128:
5722 case tok::kw_signed:
5723 case tok::kw_unsigned:
5724 case tok::kw__Complex:
5725 case tok::kw__Imaginary:
5726 case tok::kw_void:
5727 case tok::kw_char:
5728 case tok::kw_wchar_t:
5729 case tok::kw_char8_t:
5730 case tok::kw_char16_t:
5731 case tok::kw_char32_t:
5732 case tok::kw_int:
5733 case tok::kw__ExtInt:
5734 case tok::kw__BitInt:
5735 case tok::kw_half:
5736 case tok::kw___bf16:
5737 case tok::kw_float:
5738 case tok::kw_double:
5739 case tok::kw__Accum:
5740 case tok::kw__Fract:
5741 case tok::kw__Float16:
5742 case tok::kw___float128:
5743 case tok::kw___ibm128:
5744 case tok::kw_bool:
5745 case tok::kw__Bool:
5746 case tok::kw__Decimal32:
5747 case tok::kw__Decimal64:
5748 case tok::kw__Decimal128:
5749 case tok::kw___vector:
5750#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5751#include "clang/Basic/OpenCLImageTypes.def"
5752
5753 // struct-or-union-specifier (C99) or class-specifier (C++)
5754 case tok::kw_class:
5755 case tok::kw_struct:
5756 case tok::kw___interface:
5757 case tok::kw_union:
5758 // enum-specifier
5759 case tok::kw_enum:
5760
5761 // type-qualifier
5762 case tok::kw_const:
5763 case tok::kw_volatile:
5764 case tok::kw_restrict:
5765 case tok::kw__Sat:
5766
5767 // Debugger support.
5768 case tok::kw___unknown_anytype:
5769
5770 // typedef-name
5771 case tok::annot_typename:
5772 return true;
5773
5774 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5775 case tok::less:
5776 return getLangOpts().ObjC;
5777
5778 case tok::kw___cdecl:
5779 case tok::kw___stdcall:
5780 case tok::kw___fastcall:
5781 case tok::kw___thiscall:
5782 case tok::kw___regcall:
5783 case tok::kw___vectorcall:
5784 case tok::kw___w64:
5785 case tok::kw___ptr64:
5786 case tok::kw___ptr32:
5787 case tok::kw___pascal:
5788 case tok::kw___unaligned:
5789
5790 case tok::kw__Nonnull:
5791 case tok::kw__Nullable:
5792 case tok::kw__Nullable_result:
5793 case tok::kw__Null_unspecified:
5794
5795 case tok::kw___kindof:
5796
5797 case tok::kw___private:
5798 case tok::kw___local:
5799 case tok::kw___global:
5800 case tok::kw___constant:
5801 case tok::kw___generic:
5802 case tok::kw___read_only:
5803 case tok::kw___read_write:
5804 case tok::kw___write_only:
5805 case tok::kw___funcref:
5806 return true;
5807
5808 case tok::kw_private:
5809 return getLangOpts().OpenCL;
5810
5811 // C11 _Atomic
5812 case tok::kw__Atomic:
5813 return true;
5814
5815 // HLSL type qualifiers
5816 case tok::kw_groupshared:
5817 case tok::kw_in:
5818 case tok::kw_inout:
5819 case tok::kw_out:
5820 return getLangOpts().HLSL;
5821 }
5822}
5823
5824Parser::DeclGroupPtrTy Parser::ParseTopLevelStmtDecl() {
5825 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode");
5826
5827 // Parse a top-level-stmt.
5828 Parser::StmtVector Stmts;
5829 ParsedStmtContext SubStmtCtx = ParsedStmtContext();
5830 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
5833 StmtResult R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
5834 if (!R.isUsable())
5835 return nullptr;
5836
5837 Actions.ActOnFinishTopLevelStmtDecl(TLSD, R.get());
5838
5839 if (Tok.is(tok::annot_repl_input_end) &&
5840 Tok.getAnnotationValue() != nullptr) {
5841 ConsumeAnnotationToken();
5842 TLSD->setSemiMissing();
5843 }
5844
5845 SmallVector<Decl *, 2> DeclsInGroup;
5846 DeclsInGroup.push_back(TLSD);
5847
5848 // Currently happens for things like -fms-extensions and use `__if_exists`.
5849 for (Stmt *S : Stmts) {
5850 // Here we should be safe as `__if_exists` and friends are not introducing
5851 // new variables which need to live outside file scope.
5853 Actions.ActOnFinishTopLevelStmtDecl(D, S);
5854 DeclsInGroup.push_back(D);
5855 }
5856
5857 return Actions.BuildDeclaratorGroup(DeclsInGroup);
5858}
5859
5860/// isDeclarationSpecifier() - Return true if the current token is part of a
5861/// declaration specifier.
5862///
5863/// \param AllowImplicitTypename whether this is a context where T::type [T
5864/// dependent] can appear.
5865/// \param DisambiguatingWithExpression True to indicate that the purpose of
5866/// this check is to disambiguate between an expression and a declaration.
5867bool Parser::isDeclarationSpecifier(
5868 ImplicitTypenameContext AllowImplicitTypename,
5869 bool DisambiguatingWithExpression) {
5870 switch (Tok.getKind()) {
5871 default: return false;
5872
5873 // OpenCL 2.0 and later define this keyword.
5874 case tok::kw_pipe:
5875 return getLangOpts().OpenCL &&
5877
5878 case tok::identifier: // foo::bar
5879 // Unfortunate hack to support "Class.factoryMethod" notation.
5880 if (getLangOpts().ObjC && NextToken().is(tok::period))
5881 return false;
5882 if (TryAltiVecVectorToken())
5883 return true;
5884 [[fallthrough]];
5885 case tok::kw_decltype: // decltype(T())::type
5886 case tok::kw_typename: // typename T::type
5887 // Annotate typenames and C++ scope specifiers. If we get one, just
5888 // recurse to handle whatever we get.
5889 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
5890 return true;
5891 if (TryAnnotateTypeConstraint())
5892 return true;
5893 if (Tok.is(tok::identifier))
5894 return false;
5895
5896 // If we're in Objective-C and we have an Objective-C class type followed
5897 // by an identifier and then either ':' or ']', in a place where an
5898 // expression is permitted, then this is probably a class message send
5899 // missing the initial '['. In this case, we won't consider this to be
5900 // the start of a declaration.
5901 if (DisambiguatingWithExpression &&
5902 isStartOfObjCClassMessageMissingOpenBracket())
5903 return false;
5904
5905 return isDeclarationSpecifier(AllowImplicitTypename);
5906
5907 case tok::coloncolon: // ::foo::bar
5908 if (!getLangOpts().CPlusPlus)
5909 return false;
5910 if (NextToken().is(tok::kw_new) || // ::new
5911 NextToken().is(tok::kw_delete)) // ::delete
5912 return false;
5913
5914 // Annotate typenames and C++ scope specifiers. If we get one, just
5915 // recurse to handle whatever we get.
5917 return true;
5918 return isDeclarationSpecifier(ImplicitTypenameContext::No);
5919
5920 // storage-class-specifier
5921 case tok::kw_typedef:
5922 case tok::kw_extern:
5923 case tok::kw___private_extern__:
5924 case tok::kw_static:
5925 case tok::kw_auto:
5926 case tok::kw___auto_type:
5927 case tok::kw_register:
5928 case tok::kw___thread:
5929 case tok::kw_thread_local:
5930 case tok::kw__Thread_local:
5931
5932 // Modules
5933 case tok::kw___module_private__:
5934
5935 // Debugger support
5936 case tok::kw___unknown_anytype:
5937
5938 // type-specifiers
5939 case tok::kw_short:
5940 case tok::kw_long:
5941 case tok::kw___int64:
5942 case tok::kw___int128:
5943 case tok::kw_signed:
5944 case tok::kw_unsigned:
5945 case tok::kw__Complex:
5946 case tok::kw__Imaginary:
5947 case tok::kw_void:
5948 case tok::kw_char:
5949 case tok::kw_wchar_t:
5950 case tok::kw_char8_t:
5951 case tok::kw_char16_t:
5952 case tok::kw_char32_t:
5953
5954 case tok::kw_int:
5955 case tok::kw__ExtInt:
5956 case tok::kw__BitInt:
5957 case tok::kw_half:
5958 case tok::kw___bf16:
5959 case tok::kw_float:
5960 case tok::kw_double:
5961 case tok::kw__Accum:
5962 case tok::kw__Fract:
5963 case tok::kw__Float16:
5964 case tok::kw___float128:
5965 case tok::kw___ibm128:
5966 case tok::kw_bool:
5967 case tok::kw__Bool:
5968 case tok::kw__Decimal32:
5969 case tok::kw__Decimal64:
5970 case tok::kw__Decimal128:
5971 case tok::kw___vector:
5972
5973 // struct-or-union-specifier (C99) or class-specifier (C++)
5974 case tok::kw_class:
5975 case tok::kw_struct:
5976 case tok::kw_union:
5977 case tok::kw___interface:
5978 // enum-specifier
5979 case tok::kw_enum:
5980
5981 // type-qualifier
5982 case tok::kw_const:
5983 case tok::kw_volatile:
5984 case tok::kw_restrict:
5985 case tok::kw__Sat:
5986
5987 // function-specifier
5988 case tok::kw_inline:
5989 case tok::kw_virtual:
5990 case tok::kw_explicit:
5991 case tok::kw__Noreturn:
5992
5993 // alignment-specifier
5994 case tok::kw__Alignas:
5995
5996 // friend keyword.
5997 case tok::kw_friend:
5998
5999 // static_assert-declaration
6000 case tok::kw_static_assert:
6001 case tok::kw__Static_assert:
6002
6003 // C23/GNU typeof support.
6004 case tok::kw_typeof:
6005 case tok::kw_typeof_unqual:
6006
6007 // GNU attributes.
6008 case tok::kw___attribute:
6009
6010 // C++11 decltype and constexpr.
6011 case tok::annot_decltype:
6012 case tok::annot_pack_indexing_type:
6013 case tok::kw_constexpr:
6014
6015 // C++20 consteval and constinit.
6016 case tok::kw_consteval:
6017 case tok::kw_constinit:
6018
6019 // C11 _Atomic
6020 case tok::kw__Atomic:
6021 return true;
6022
6023 case tok::kw_alignas:
6024 // alignas is a type-specifier-qualifier in C23, which is a kind of
6025 // declaration-specifier. Outside of C23 mode (including in C++), it is not.
6026 return getLangOpts().C23;
6027
6028 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
6029 case tok::less:
6030 return getLangOpts().ObjC;
6031
6032 // typedef-name
6033 case tok::annot_typename:
6034 return !DisambiguatingWithExpression ||
6035 !isStartOfObjCClassMessageMissingOpenBracket();
6036
6037 // placeholder-type-specifier
6038 case tok::annot_template_id: {
6039 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
6040 if (TemplateId->hasInvalidName())
6041 return true;
6042 // FIXME: What about type templates that have only been annotated as
6043 // annot_template_id, not as annot_typename?
6044 return isTypeConstraintAnnotation() &&
6045 (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
6046 }
6047
6048 case tok::annot_cxxscope: {
6049 TemplateIdAnnotation *TemplateId =
6050 NextToken().is(tok::annot_template_id)
6051 ? takeTemplateIdAnnotation(NextToken())
6052 : nullptr;
6053 if (TemplateId && TemplateId->hasInvalidName())
6054 return true;
6055 // FIXME: What about type templates that have only been annotated as
6056 // annot_template_id, not as annot_typename?
6057 if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
6058 return true;
6059 return isTypeConstraintAnnotation() &&
6060 GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
6061 }
6062
6063 case tok::kw___declspec:
6064 case tok::kw___cdecl:
6065 case tok::kw___stdcall:
6066 case tok::kw___fastcall:
6067 case tok::kw___thiscall:
6068 case tok::kw___regcall:
6069 case tok::kw___vectorcall:
6070 case tok::kw___w64:
6071 case tok::kw___sptr:
6072 case tok::kw___uptr:
6073 case tok::kw___ptr64:
6074 case tok::kw___ptr32:
6075 case tok::kw___forceinline:
6076 case tok::kw___pascal:
6077 case tok::kw___unaligned:
6078
6079 case tok::kw__Nonnull:
6080 case tok::kw__Nullable:
6081 case tok::kw__Nullable_result:
6082 case tok::kw__Null_unspecified:
6083
6084 case tok::kw___kindof:
6085
6086 case tok::kw___private:
6087 case tok::kw___local:
6088 case tok::kw___global:
6089 case tok::kw___constant:
6090 case tok::kw___generic:
6091 case tok::kw___read_only:
6092 case tok::kw___read_write:
6093 case tok::kw___write_only:
6094#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
6095#include "clang/Basic/OpenCLImageTypes.def"
6096
6097 case tok::kw___funcref:
6098 case tok::kw_groupshared:
6099 return true;
6100
6101 case tok::kw_private:
6102 return getLangOpts().OpenCL;
6103 }
6104}
6105
6106bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide,
6108 const ParsedTemplateInfo *TemplateInfo) {
6109 RevertingTentativeParsingAction TPA(*this);
6110 // Parse the C++ scope specifier.
6111 CXXScopeSpec SS;
6112 if (TemplateInfo && TemplateInfo->TemplateParams)
6113 SS.setTemplateParamLists(*TemplateInfo->TemplateParams);
6114
6115 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6116 /*ObjectHasErrors=*/false,
6117 /*EnteringContext=*/true)) {
6118 return false;
6119 }
6120
6121 // Parse the constructor name.
6122 if (Tok.is(tok::identifier)) {
6123 // We already know that we have a constructor name; just consume
6124 // the token.
6125 ConsumeToken();
6126 } else if (Tok.is(tok::annot_template_id)) {
6127 ConsumeAnnotationToken();
6128 } else {
6129 return false;
6130 }
6131
6132 // There may be attributes here, appertaining to the constructor name or type
6133 // we just stepped past.
6134 SkipCXX11Attributes();
6135
6136 // Current class name must be followed by a left parenthesis.
6137 if (Tok.isNot(tok::l_paren)) {
6138 return false;
6139 }
6140 ConsumeParen();
6141
6142 // A right parenthesis, or ellipsis followed by a right parenthesis signals
6143 // that we have a constructor.
6144 if (Tok.is(tok::r_paren) ||
6145 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
6146 return true;
6147 }
6148
6149 // A C++11 attribute here signals that we have a constructor, and is an
6150 // attribute on the first constructor parameter.
6151 if (getLangOpts().CPlusPlus11 &&
6152 isCXX11AttributeSpecifier(/*Disambiguate*/ false,
6153 /*OuterMightBeMessageSend*/ true)) {
6154 return true;
6155 }
6156
6157 // If we need to, enter the specified scope.
6158 DeclaratorScopeObj DeclScopeObj(*this, SS);
6159 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
6160 DeclScopeObj.EnterDeclaratorScope();
6161
6162 // Optionally skip Microsoft attributes.
6163 ParsedAttributes Attrs(AttrFactory);
6164 MaybeParseMicrosoftAttributes(Attrs);
6165
6166 // Check whether the next token(s) are part of a declaration
6167 // specifier, in which case we have the start of a parameter and,
6168 // therefore, we know that this is a constructor.
6169 // Due to an ambiguity with implicit typename, the above is not enough.
6170 // Additionally, check to see if we are a friend.
6171 // If we parsed a scope specifier as well as friend,
6172 // we might be parsing a friend constructor.
6173 bool IsConstructor = false;
6174 ImplicitTypenameContext ITC = IsFriend && !SS.isSet()
6177 // Constructors cannot have this parameters, but we support that scenario here
6178 // to improve diagnostic.
6179 if (Tok.is(tok::kw_this)) {
6180 ConsumeToken();
6181 return isDeclarationSpecifier(ITC);
6182 }
6183
6184 if (isDeclarationSpecifier(ITC))
6185 IsConstructor = true;
6186 else if (Tok.is(tok::identifier) ||
6187 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
6188 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
6189 // This might be a parenthesized member name, but is more likely to
6190 // be a constructor declaration with an invalid argument type. Keep
6191 // looking.
6192 if (Tok.is(tok::annot_cxxscope))
6193 ConsumeAnnotationToken();
6194 ConsumeToken();
6195
6196 // If this is not a constructor, we must be parsing a declarator,
6197 // which must have one of the following syntactic forms (see the
6198 // grammar extract at the start of ParseDirectDeclarator):
6199 switch (Tok.getKind()) {
6200 case tok::l_paren:
6201 // C(X ( int));
6202 case tok::l_square:
6203 // C(X [ 5]);
6204 // C(X [ [attribute]]);
6205 case tok::coloncolon:
6206 // C(X :: Y);
6207 // C(X :: *p);
6208 // Assume this isn't a constructor, rather than assuming it's a
6209 // constructor with an unnamed parameter of an ill-formed type.
6210 break;
6211
6212 case tok::r_paren:
6213 // C(X )
6214
6215 // Skip past the right-paren and any following attributes to get to
6216 // the function body or trailing-return-type.
6217 ConsumeParen();
6218 SkipCXX11Attributes();
6219
6220 if (DeductionGuide) {
6221 // C(X) -> ... is a deduction guide.
6222 IsConstructor = Tok.is(tok::arrow);
6223 break;
6224 }
6225 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
6226 // Assume these were meant to be constructors:
6227 // C(X) : (the name of a bit-field cannot be parenthesized).
6228 // C(X) try (this is otherwise ill-formed).
6229 IsConstructor = true;
6230 }
6231 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
6232 // If we have a constructor name within the class definition,
6233 // assume these were meant to be constructors:
6234 // C(X) {
6235 // C(X) ;
6236 // ... because otherwise we would be declaring a non-static data
6237 // member that is ill-formed because it's of the same type as its
6238 // surrounding class.
6239 //
6240 // FIXME: We can actually do this whether or not the name is qualified,
6241 // because if it is qualified in this context it must be being used as
6242 // a constructor name.
6243 // currently, so we're somewhat conservative here.
6244 IsConstructor = IsUnqualified;
6245 }
6246 break;
6247
6248 default:
6249 IsConstructor = true;
6250 break;
6251 }
6252 }
6253 return IsConstructor;
6254}
6255
6256/// ParseTypeQualifierListOpt
6257/// type-qualifier-list: [C99 6.7.5]
6258/// type-qualifier
6259/// [vendor] attributes
6260/// [ only if AttrReqs & AR_VendorAttributesParsed ]
6261/// type-qualifier-list type-qualifier
6262/// [vendor] type-qualifier-list attributes
6263/// [ only if AttrReqs & AR_VendorAttributesParsed ]
6264/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
6265/// [ only if AttReqs & AR_CXX11AttributesParsed ]
6266/// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
6267/// AttrRequirements bitmask values.
6268void Parser::ParseTypeQualifierListOpt(
6269 DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
6270 bool IdentifierRequired,
6271 std::optional<llvm::function_ref<void()>> CodeCompletionHandler) {
6272 if ((AttrReqs & AR_CXX11AttributesParsed) &&
6273 isAllowedCXX11AttributeSpecifier()) {
6274 ParsedAttributes Attrs(AttrFactory);
6275 ParseCXX11Attributes(Attrs);
6276 DS.takeAttributesFrom(Attrs);
6277 }
6278
6279 SourceLocation EndLoc;
6280
6281 while (true) {
6282 bool isInvalid = false;
6283 const char *PrevSpec = nullptr;
6284 unsigned DiagID = 0;
6286
6287 switch (Tok.getKind()) {
6288 case tok::code_completion:
6289 cutOffParsing();
6291 (*CodeCompletionHandler)();
6292 else
6294 return;
6295
6296 case tok::kw_const:
6297 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
6298 getLangOpts());
6299 break;
6300 case tok::kw_volatile:
6301 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
6302 getLangOpts());
6303 break;
6304 case tok::kw_restrict:
6305 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
6306 getLangOpts());
6307 break;
6308 case tok::kw__Atomic:
6309 if (!AtomicAllowed)
6310 goto DoneWithTypeQuals;
6311 diagnoseUseOfC11Keyword(Tok);
6312 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
6313 getLangOpts());
6314 break;
6315
6316 // OpenCL qualifiers:
6317 case tok::kw_private:
6318 if (!getLangOpts().OpenCL)
6319 goto DoneWithTypeQuals;
6320 [[fallthrough]];
6321 case tok::kw___private:
6322 case tok::kw___global:
6323 case tok::kw___local:
6324 case tok::kw___constant:
6325 case tok::kw___generic:
6326 case tok::kw___read_only:
6327 case tok::kw___write_only:
6328 case tok::kw___read_write:
6329 ParseOpenCLQualifiers(DS.getAttributes());
6330 break;
6331
6332 case tok::kw_groupshared:
6333 case tok::kw_in:
6334 case tok::kw_inout:
6335 case tok::kw_out:
6336 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
6337 ParseHLSLQualifiers(DS.getAttributes());
6338 continue;
6339
6340 case tok::kw___unaligned:
6341 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
6342 getLangOpts());
6343 break;
6344 case tok::kw___uptr:
6345 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
6346 // with the MS modifier keyword.
6347 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
6348 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
6349 if (TryKeywordIdentFallback(false))
6350 continue;
6351 }
6352 [[fallthrough]];
6353 case tok::kw___sptr:
6354 case tok::kw___w64:
6355 case tok::kw___ptr64:
6356 case tok::kw___ptr32:
6357 case tok::kw___cdecl:
6358 case tok::kw___stdcall:
6359 case tok::kw___fastcall:
6360 case tok::kw___thiscall:
6361 case tok::kw___regcall:
6362 case tok::kw___vectorcall:
6363 if (AttrReqs & AR_DeclspecAttributesParsed) {
6364 ParseMicrosoftTypeAttributes(DS.getAttributes());
6365 continue;
6366 }
6367 goto DoneWithTypeQuals;
6368
6369 case tok::kw___funcref:
6370 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
6371 continue;
6372 goto DoneWithTypeQuals;
6373
6374 case tok::kw___pascal:
6375 if (AttrReqs & AR_VendorAttributesParsed) {
6376 ParseBorlandTypeAttributes(DS.getAttributes());
6377 continue;
6378 }
6379 goto DoneWithTypeQuals;
6380
6381 // Nullability type specifiers.
6382 case tok::kw__Nonnull:
6383 case tok::kw__Nullable:
6384 case tok::kw__Nullable_result:
6385 case tok::kw__Null_unspecified:
6386 ParseNullabilityTypeSpecifiers(DS.getAttributes());
6387 continue;
6388
6389 // Objective-C 'kindof' types.
6390 case tok::kw___kindof:
6391 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
6392 nullptr, 0, tok::kw___kindof);
6393 (void)ConsumeToken();
6394 continue;
6395
6396 case tok::kw___attribute:
6397 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
6398 // When GNU attributes are expressly forbidden, diagnose their usage.
6399 Diag(Tok, diag::err_attributes_not_allowed);
6400
6401 // Parse the attributes even if they are rejected to ensure that error
6402 // recovery is graceful.
6403 if (AttrReqs & AR_GNUAttributesParsed ||
6404 AttrReqs & AR_GNUAttributesParsedAndRejected) {
6405 ParseGNUAttributes(DS.getAttributes());
6406 continue; // do *not* consume the next token!
6407 }
6408 // otherwise, FALL THROUGH!
6409 [[fallthrough]];
6410 default:
6411 DoneWithTypeQuals:
6412 // If this is not a type-qualifier token, we're done reading type
6413 // qualifiers. First verify that DeclSpec's are consistent.
6414 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
6415 if (EndLoc.isValid())
6416 DS.SetRangeEnd(EndLoc);
6417 return;
6418 }
6419
6420 // If the specifier combination wasn't legal, issue a diagnostic.
6421 if (isInvalid) {
6422 assert(PrevSpec && "Method did not return previous specifier!");
6423 Diag(Tok, DiagID) << PrevSpec;
6424 }
6425 EndLoc = ConsumeToken();
6426 }
6427}
6428
6429/// ParseDeclarator - Parse and verify a newly-initialized declarator.
6430void Parser::ParseDeclarator(Declarator &D) {
6431 /// This implements the 'declarator' production in the C grammar, then checks
6432 /// for well-formedness and issues diagnostics.
6433 Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
6434 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6435 });
6436}
6437
6438static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
6439 DeclaratorContext TheContext) {
6440 if (Kind == tok::star || Kind == tok::caret)
6441 return true;
6442
6443 // OpenCL 2.0 and later define this keyword.
6444 if (Kind == tok::kw_pipe && Lang.OpenCL &&
6445 Lang.getOpenCLCompatibleVersion() >= 200)
6446 return true;
6447
6448 if (!Lang.CPlusPlus)
6449 return false;
6450
6451 if (Kind == tok::amp)
6452 return true;
6453
6454 // We parse rvalue refs in C++03, because otherwise the errors are scary.
6455 // But we must not parse them in conversion-type-ids and new-type-ids, since
6456 // those can be legitimately followed by a && operator.
6457 // (The same thing can in theory happen after a trailing-return-type, but
6458 // since those are a C++11 feature, there is no rejects-valid issue there.)
6459 if (Kind == tok::ampamp)
6460 return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId &&
6461 TheContext != DeclaratorContext::CXXNew);
6462
6463 return false;
6464}
6465
6466// Indicates whether the given declarator is a pipe declarator.
6467static bool isPipeDeclarator(const Declarator &D) {
6468 const unsigned NumTypes = D.getNumTypeObjects();
6469
6470 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
6472 return true;
6473
6474 return false;
6475}
6476
6477/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
6478/// is parsed by the function passed to it. Pass null, and the direct-declarator
6479/// isn't parsed at all, making this function effectively parse the C++
6480/// ptr-operator production.
6481///
6482/// If the grammar of this construct is extended, matching changes must also be
6483/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
6484/// isConstructorDeclarator.
6485///
6486/// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
6487/// [C] pointer[opt] direct-declarator
6488/// [C++] direct-declarator
6489/// [C++] ptr-operator declarator
6490///
6491/// pointer: [C99 6.7.5]
6492/// '*' type-qualifier-list[opt]
6493/// '*' type-qualifier-list[opt] pointer
6494///
6495/// ptr-operator:
6496/// '*' cv-qualifier-seq[opt]
6497/// '&'
6498/// [C++0x] '&&'
6499/// [GNU] '&' restrict[opt] attributes[opt]
6500/// [GNU?] '&&' restrict[opt] attributes[opt]
6501/// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
6502void Parser::ParseDeclaratorInternal(Declarator &D,
6503 DirectDeclParseFunction DirectDeclParser) {
6504 if (Diags.hasAllExtensionsSilenced())
6505 D.setExtension();
6506
6507 // C++ member pointers start with a '::' or a nested-name.
6508 // Member pointers get special handling, since there's no place for the
6509 // scope spec in the generic path below.
6510 if (getLangOpts().CPlusPlus &&
6511 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
6512 (Tok.is(tok::identifier) &&
6513 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
6514 Tok.is(tok::annot_cxxscope))) {
6515 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6517 CXXScopeSpec SS;
6519 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6520 /*ObjectHasErrors=*/false, EnteringContext);
6521
6522 if (SS.isNotEmpty()) {
6523 if (Tok.isNot(tok::star)) {
6524 // The scope spec really belongs to the direct-declarator.
6525 if (D.mayHaveIdentifier())
6526 D.getCXXScopeSpec() = SS;
6527 else
6528 AnnotateScopeToken(SS, true);
6529
6530 if (DirectDeclParser)
6531 (this->*DirectDeclParser)(D);
6532 return;
6533 }
6534
6535 if (SS.isValid()) {
6536 checkCompoundToken(SS.getEndLoc(), tok::coloncolon,
6537 CompoundToken::MemberPtr);
6538 }
6539
6540 SourceLocation StarLoc = ConsumeToken();
6541 D.SetRangeEnd(StarLoc);
6542 DeclSpec DS(AttrFactory);
6543 ParseTypeQualifierListOpt(DS);
6544 D.ExtendWithDeclSpec(DS);
6545
6546 // Recurse to parse whatever is left.
6547 Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
6548 ParseDeclaratorInternal(D, DirectDeclParser);
6549 });
6550
6551 // Sema will have to catch (syntactically invalid) pointers into global
6552 // scope. It has to catch pointers into namespace scope anyway.
6554 SS, DS.getTypeQualifiers(), StarLoc, DS.getEndLoc()),
6555 std::move(DS.getAttributes()),
6556 /* Don't replace range end. */ SourceLocation());
6557 return;
6558 }
6559 }
6560
6561 tok::TokenKind Kind = Tok.getKind();
6562
6563 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclarator(D)) {
6564 DeclSpec DS(AttrFactory);
6565 ParseTypeQualifierListOpt(DS);
6566
6567 D.AddTypeInfo(
6569 std::move(DS.getAttributes()), SourceLocation());
6570 }
6571
6572 // Not a pointer, C++ reference, or block.
6573 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
6574 if (DirectDeclParser)
6575 (this->*DirectDeclParser)(D);
6576 return;
6577 }
6578
6579 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
6580 // '&&' -> rvalue reference
6581 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
6582 D.SetRangeEnd(Loc);
6583
6584 if (Kind == tok::star || Kind == tok::caret) {
6585 // Is a pointer.
6586 DeclSpec DS(AttrFactory);
6587
6588 // GNU attributes are not allowed here in a new-type-id, but Declspec and
6589 // C++11 attributes are allowed.
6590 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
6592 ? AR_GNUAttributesParsed
6593 : AR_GNUAttributesParsedAndRejected);
6594 ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
6595 D.ExtendWithDeclSpec(DS);
6596
6597 // Recursively parse the declarator.
6599 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6600 if (Kind == tok::star)
6601 // Remember that we parsed a pointer type, and remember the type-quals.
6606 std::move(DS.getAttributes()), SourceLocation());
6607 else
6608 // Remember that we parsed a Block type, and remember the type-quals.
6609 D.AddTypeInfo(
6611 std::move(DS.getAttributes()), SourceLocation());
6612 } else {
6613 // Is a reference
6614 DeclSpec DS(AttrFactory);
6615
6616 // Complain about rvalue references in C++03, but then go on and build
6617 // the declarator.
6618 if (Kind == tok::ampamp)
6620 diag::warn_cxx98_compat_rvalue_reference :
6621 diag::ext_rvalue_reference);
6622
6623 // GNU-style and C++11 attributes are allowed here, as is restrict.
6624 ParseTypeQualifierListOpt(DS);
6625 D.ExtendWithDeclSpec(DS);
6626
6627 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
6628 // cv-qualifiers are introduced through the use of a typedef or of a
6629 // template type argument, in which case the cv-qualifiers are ignored.
6632 Diag(DS.getConstSpecLoc(),
6633 diag::err_invalid_reference_qualifier_application) << "const";
6636 diag::err_invalid_reference_qualifier_application) << "volatile";
6637 // 'restrict' is permitted as an extension.
6640 diag::err_invalid_reference_qualifier_application) << "_Atomic";
6641 }
6642
6643 // Recursively parse the declarator.
6645 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6646
6647 if (D.getNumTypeObjects() > 0) {
6648 // C++ [dcl.ref]p4: There shall be no references to references.
6649 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
6650 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
6651 if (const IdentifierInfo *II = D.getIdentifier())
6652 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6653 << II;
6654 else
6655 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6656 << "type name";
6657
6658 // Once we've complained about the reference-to-reference, we
6659 // can go ahead and build the (technically ill-formed)
6660 // declarator: reference collapsing will take care of it.
6661 }
6662 }
6663
6664 // Remember that we parsed a reference type.
6666 Kind == tok::amp),
6667 std::move(DS.getAttributes()), SourceLocation());
6668 }
6669}
6670
6671// When correcting from misplaced brackets before the identifier, the location
6672// is saved inside the declarator so that other diagnostic messages can use
6673// them. This extracts and returns that location, or returns the provided
6674// location if a stored location does not exist.
6677 if (D.getName().StartLocation.isInvalid() &&
6679 return D.getName().EndLocation;
6680
6681 return Loc;
6682}
6683
6684/// ParseDirectDeclarator
6685/// direct-declarator: [C99 6.7.5]
6686/// [C99] identifier
6687/// '(' declarator ')'
6688/// [GNU] '(' attributes declarator ')'
6689/// [C90] direct-declarator '[' constant-expression[opt] ']'
6690/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6691/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6692/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6693/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
6694/// [C++11] direct-declarator '[' constant-expression[opt] ']'
6695/// attribute-specifier-seq[opt]
6696/// direct-declarator '(' parameter-type-list ')'
6697/// direct-declarator '(' identifier-list[opt] ')'
6698/// [GNU] direct-declarator '(' parameter-forward-declarations
6699/// parameter-type-list[opt] ')'
6700/// [C++] direct-declarator '(' parameter-declaration-clause ')'
6701/// cv-qualifier-seq[opt] exception-specification[opt]
6702/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
6703/// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
6704/// ref-qualifier[opt] exception-specification[opt]
6705/// [C++] declarator-id
6706/// [C++11] declarator-id attribute-specifier-seq[opt]
6707///
6708/// declarator-id: [C++ 8]
6709/// '...'[opt] id-expression
6710/// '::'[opt] nested-name-specifier[opt] type-name
6711///
6712/// id-expression: [C++ 5.1]
6713/// unqualified-id
6714/// qualified-id
6715///
6716/// unqualified-id: [C++ 5.1]
6717/// identifier
6718/// operator-function-id
6719/// conversion-function-id
6720/// '~' class-name
6721/// template-id
6722///
6723/// C++17 adds the following, which we also handle here:
6724///
6725/// simple-declaration:
6726/// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
6727///
6728/// Note, any additional constructs added here may need corresponding changes
6729/// in isConstructorDeclarator.
6730void Parser::ParseDirectDeclarator(Declarator &D) {
6731 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
6732
6734 // This might be a C++17 structured binding.
6735 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
6737 return ParseDecompositionDeclarator(D);
6738
6739 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
6740 // this context it is a bitfield. Also in range-based for statement colon
6741 // may delimit for-range-declaration.
6743 *this, D.getContext() == DeclaratorContext::Member ||
6746
6747 // ParseDeclaratorInternal might already have parsed the scope.
6748 if (D.getCXXScopeSpec().isEmpty()) {
6749 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6751 ParseOptionalCXXScopeSpecifier(
6752 D.getCXXScopeSpec(), /*ObjectType=*/nullptr,
6753 /*ObjectHasErrors=*/false, EnteringContext);
6754 }
6755
6756 // C++23 [basic.scope.namespace]p1:
6757 // For each non-friend redeclaration or specialization whose target scope
6758 // is or is contained by the scope, the portion after the declarator-id,
6759 // class-head-name, or enum-head-name is also included in the scope.
6760 // C++23 [basic.scope.class]p1:
6761 // For each non-friend redeclaration or specialization whose target scope
6762 // is or is contained by the scope, the portion after the declarator-id,
6763 // class-head-name, or enum-head-name is also included in the scope.
6764 //
6765 // FIXME: We should not be doing this for friend declarations; they have
6766 // their own special lookup semantics specified by [basic.lookup.unqual]p6.
6767 if (D.getCXXScopeSpec().isValid()) {
6769 D.getCXXScopeSpec()))
6770 // Change the declaration context for name lookup, until this function
6771 // is exited (and the declarator has been parsed).
6772 DeclScopeObj.EnterDeclaratorScope();
6773 else if (getObjCDeclContext()) {
6774 // Ensure that we don't interpret the next token as an identifier when
6775 // dealing with declarations in an Objective-C container.
6776 D.SetIdentifier(nullptr, Tok.getLocation());
6777 D.setInvalidType(true);
6778 ConsumeToken();
6779 goto PastIdentifier;
6780 }
6781 }
6782
6783 // C++0x [dcl.fct]p14:
6784 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
6785 // parameter-declaration-clause without a preceding comma. In this case,
6786 // the ellipsis is parsed as part of the abstract-declarator if the type
6787 // of the parameter either names a template parameter pack that has not
6788 // been expanded or contains auto; otherwise, it is parsed as part of the
6789 // parameter-declaration-clause.
6790 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
6794 NextToken().is(tok::r_paren) && !D.hasGroupingParens() &&
6797 SourceLocation EllipsisLoc = ConsumeToken();
6798 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
6799 // The ellipsis was put in the wrong place. Recover, and explain to
6800 // the user what they should have done.
6801 ParseDeclarator(D);
6802 if (EllipsisLoc.isValid())
6803 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6804 return;
6805 } else
6806 D.setEllipsisLoc(EllipsisLoc);
6807
6808 // The ellipsis can't be followed by a parenthesized declarator. We
6809 // check for that in ParseParenDeclarator, after we have disambiguated
6810 // the l_paren token.
6811 }
6812
6813 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
6814 tok::tilde)) {
6815 // We found something that indicates the start of an unqualified-id.
6816 // Parse that unqualified-id.
6817 bool AllowConstructorName;
6818 bool AllowDeductionGuide;
6819 if (D.getDeclSpec().hasTypeSpecifier()) {
6820 AllowConstructorName = false;
6821 AllowDeductionGuide = false;
6822 } else if (D.getCXXScopeSpec().isSet()) {
6823 AllowConstructorName = (D.getContext() == DeclaratorContext::File ||
6825 AllowDeductionGuide = false;
6826 } else {
6827 AllowConstructorName = (D.getContext() == DeclaratorContext::Member);
6828 AllowDeductionGuide = (D.getContext() == DeclaratorContext::File ||
6830 }
6831
6832 bool HadScope = D.getCXXScopeSpec().isValid();
6833 SourceLocation TemplateKWLoc;
6835 /*ObjectType=*/nullptr,
6836 /*ObjectHadErrors=*/false,
6837 /*EnteringContext=*/true,
6838 /*AllowDestructorName=*/true, AllowConstructorName,
6839 AllowDeductionGuide, &TemplateKWLoc,
6840 D.getName()) ||
6841 // Once we're past the identifier, if the scope was bad, mark the
6842 // whole declarator bad.
6843 D.getCXXScopeSpec().isInvalid()) {
6844 D.SetIdentifier(nullptr, Tok.getLocation());
6845 D.setInvalidType(true);
6846 } else {
6847 // ParseUnqualifiedId might have parsed a scope specifier during error
6848 // recovery. If it did so, enter that scope.
6849 if (!HadScope && D.getCXXScopeSpec().isValid() &&
6851 D.getCXXScopeSpec()))
6852 DeclScopeObj.EnterDeclaratorScope();
6853
6854 // Parsed the unqualified-id; update range information and move along.
6855 if (D.getSourceRange().getBegin().isInvalid())
6858 }
6859 goto PastIdentifier;
6860 }
6861
6862 if (D.getCXXScopeSpec().isNotEmpty()) {
6863 // We have a scope specifier but no following unqualified-id.
6865 diag::err_expected_unqualified_id)
6866 << /*C++*/1;
6867 D.SetIdentifier(nullptr, Tok.getLocation());
6868 goto PastIdentifier;
6869 }
6870 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
6871 assert(!getLangOpts().CPlusPlus &&
6872 "There's a C++-specific check for tok::identifier above");
6873 assert(Tok.getIdentifierInfo() && "Not an identifier?");
6875 D.SetRangeEnd(Tok.getLocation());
6876 ConsumeToken();
6877 goto PastIdentifier;
6878 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
6879 // We're not allowed an identifier here, but we got one. Try to figure out
6880 // if the user was trying to attach a name to the type, or whether the name
6881 // is some unrelated trailing syntax.
6882 bool DiagnoseIdentifier = false;
6883 if (D.hasGroupingParens())
6884 // An identifier within parens is unlikely to be intended to be anything
6885 // other than a name being "declared".
6886 DiagnoseIdentifier = true;
6888 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
6889 DiagnoseIdentifier =
6890 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
6891 else if (D.getContext() == DeclaratorContext::AliasDecl ||
6893 // The most likely error is that the ';' was forgotten.
6894 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
6897 !isCXX11VirtSpecifier(Tok))
6898 DiagnoseIdentifier = NextToken().isOneOf(
6899 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
6900 if (DiagnoseIdentifier) {
6901 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
6903 D.SetIdentifier(nullptr, Tok.getLocation());
6904 ConsumeToken();
6905 goto PastIdentifier;
6906 }
6907 }
6908
6909 if (Tok.is(tok::l_paren)) {
6910 // If this might be an abstract-declarator followed by a direct-initializer,
6911 // check whether this is a valid declarator chunk. If it can't be, assume
6912 // that it's an initializer instead.
6914 RevertingTentativeParsingAction PA(*this);
6915 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true,
6917 TPResult::False) {
6918 D.SetIdentifier(nullptr, Tok.getLocation());
6919 goto PastIdentifier;
6920 }
6921 }
6922
6923 // direct-declarator: '(' declarator ')'
6924 // direct-declarator: '(' attributes declarator ')'
6925 // Example: 'char (*X)' or 'int (*XX)(void)'
6926 ParseParenDeclarator(D);
6927
6928 // If the declarator was parenthesized, we entered the declarator
6929 // scope when parsing the parenthesized declarator, then exited
6930 // the scope already. Re-enter the scope, if we need to.
6931 if (D.getCXXScopeSpec().isSet()) {
6932 // If there was an error parsing parenthesized declarator, declarator
6933 // scope may have been entered before. Don't do it again.
6934 if (!D.isInvalidType() &&
6936 D.getCXXScopeSpec()))
6937 // Change the declaration context for name lookup, until this function
6938 // is exited (and the declarator has been parsed).
6939 DeclScopeObj.EnterDeclaratorScope();
6940 }
6941 } else if (D.mayOmitIdentifier()) {
6942 // This could be something simple like "int" (in which case the declarator
6943 // portion is empty), if an abstract-declarator is allowed.
6944 D.SetIdentifier(nullptr, Tok.getLocation());
6945
6946 // The grammar for abstract-pack-declarator does not allow grouping parens.
6947 // FIXME: Revisit this once core issue 1488 is resolved.
6948 if (D.hasEllipsis() && D.hasGroupingParens())
6950 diag::ext_abstract_pack_declarator_parens);
6951 } else {
6952 if (Tok.getKind() == tok::annot_pragma_parser_crash)
6953 LLVM_BUILTIN_TRAP;
6954 if (Tok.is(tok::l_square))
6955 return ParseMisplacedBracketDeclarator(D);
6957 // Objective-C++: Detect C++ keywords and try to prevent further errors by
6958 // treating these keyword as valid member names.
6960 !Tok.isAnnotation() && Tok.getIdentifierInfo() &&
6963 diag::err_expected_member_name_or_semi_objcxx_keyword)
6964 << Tok.getIdentifierInfo()
6965 << (D.getDeclSpec().isEmpty() ? SourceRange()
6966 : D.getDeclSpec().getSourceRange());
6968 D.SetRangeEnd(Tok.getLocation());
6969 ConsumeToken();
6970 goto PastIdentifier;
6971 }
6973 diag::err_expected_member_name_or_semi)
6974 << (D.getDeclSpec().isEmpty() ? SourceRange()
6975 : D.getDeclSpec().getSourceRange());
6976 } else {
6977 if (Tok.getKind() == tok::TokenKind::kw_while) {
6978 Diag(Tok, diag::err_while_loop_outside_of_a_function);
6979 } else if (getLangOpts().CPlusPlus) {
6980 if (Tok.isOneOf(tok::period, tok::arrow))
6981 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
6982 else {
6984 if (Tok.isAtStartOfLine() && Loc.isValid())
6985 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
6986 << getLangOpts().CPlusPlus;
6987 else
6989 diag::err_expected_unqualified_id)
6990 << getLangOpts().CPlusPlus;
6991 }
6992 } else {
6994 diag::err_expected_either)
6995 << tok::identifier << tok::l_paren;
6996 }
6997 }
6998 D.SetIdentifier(nullptr, Tok.getLocation());
6999 D.setInvalidType(true);
7000 }
7001
7002 PastIdentifier:
7003 assert(D.isPastIdentifier() &&
7004 "Haven't past the location of the identifier yet?");
7005
7006 // Don't parse attributes unless we have parsed an unparenthesized name.
7007 if (D.hasName() && !D.getNumTypeObjects())
7008 MaybeParseCXX11Attributes(D);
7009
7010 while (true) {
7011 if (Tok.is(tok::l_paren)) {
7012 bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
7013 // Enter function-declaration scope, limiting any declarators to the
7014 // function prototype scope, including parameter declarators.
7015 ParseScope PrototypeScope(this,
7017 (IsFunctionDeclaration
7019
7020 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
7021 // In such a case, check if we actually have a function declarator; if it
7022 // is not, the declarator has been fully parsed.
7023 bool IsAmbiguous = false;
7025 // C++2a [temp.res]p5
7026 // A qualified-id is assumed to name a type if
7027 // - [...]
7028 // - it is a decl-specifier of the decl-specifier-seq of a
7029 // - [...]
7030 // - parameter-declaration in a member-declaration [...]
7031 // - parameter-declaration in a declarator of a function or function
7032 // template declaration whose declarator-id is qualified [...]
7033 auto AllowImplicitTypename = ImplicitTypenameContext::No;
7034 if (D.getCXXScopeSpec().isSet())
7035 AllowImplicitTypename =
7037 else if (D.getContext() == DeclaratorContext::Member) {
7038 AllowImplicitTypename = ImplicitTypenameContext::Yes;
7039 }
7040
7041 // The name of the declarator, if any, is tentatively declared within
7042 // a possible direct initializer.
7043 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
7044 bool IsFunctionDecl =
7045 isCXXFunctionDeclarator(&IsAmbiguous, AllowImplicitTypename);
7046 TentativelyDeclaredIdentifiers.pop_back();
7047 if (!IsFunctionDecl)
7048 break;
7049 }
7050 ParsedAttributes attrs(AttrFactory);
7051 BalancedDelimiterTracker T(*this, tok::l_paren);
7052 T.consumeOpen();
7053 if (IsFunctionDeclaration)
7055 TemplateParameterDepth);
7056 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
7057 if (IsFunctionDeclaration)
7059 PrototypeScope.Exit();
7060 } else if (Tok.is(tok::l_square)) {
7061 ParseBracketDeclarator(D);
7062 } else if (Tok.isRegularKeywordAttribute()) {
7063 // For consistency with attribute parsing.
7064 Diag(Tok, diag::err_keyword_not_allowed) << Tok.getIdentifierInfo();
7065 bool TakesArgs = doesKeywordAttributeTakeArgs(Tok.getKind());
7066 ConsumeToken();
7067 if (TakesArgs) {
7068 BalancedDelimiterTracker T(*this, tok::l_paren);
7069 if (!T.consumeOpen())
7070 T.skipToEnd();
7071 }
7072 } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
7073 // This declarator is declaring a function, but the requires clause is
7074 // in the wrong place:
7075 // void (f() requires true);
7076 // instead of
7077 // void f() requires true;
7078 // or
7079 // void (f()) requires true;
7080 Diag(Tok, diag::err_requires_clause_inside_parens);
7081 ConsumeToken();
7082 ExprResult TrailingRequiresClause = Actions.CorrectDelayedTyposInExpr(
7083 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
7084 if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
7086 // We're already ill-formed if we got here but we'll accept it anyway.
7087 D.setTrailingRequiresClause(TrailingRequiresClause.get());
7088 } else {
7089 break;
7090 }
7091 }
7092}
7093
7094void Parser::ParseDecompositionDeclarator(Declarator &D) {
7095 assert(Tok.is(tok::l_square));
7096
7097 TentativeParsingAction PA(*this);
7098 BalancedDelimiterTracker T(*this, tok::l_square);
7099 T.consumeOpen();
7100
7101 if (isCXX11AttributeSpecifier())
7102 DiagnoseAndSkipCXX11Attributes();
7103
7104 // If this doesn't look like a structured binding, maybe it's a misplaced
7105 // array declarator.
7106 if (!(Tok.is(tok::identifier) &&
7107 NextToken().isOneOf(tok::comma, tok::r_square, tok::kw_alignas,
7108 tok::l_square)) &&
7109 !(Tok.is(tok::r_square) &&
7110 NextToken().isOneOf(tok::equal, tok::l_brace))) {
7111 PA.Revert();
7112 return ParseMisplacedBracketDeclarator(D);
7113 }
7114
7116 while (Tok.isNot(tok::r_square)) {
7117 if (!Bindings.empty()) {
7118 if (Tok.is(tok::comma))
7119 ConsumeToken();
7120 else {
7121 if (Tok.is(tok::identifier)) {
7123 Diag(EndLoc, diag::err_expected)
7124 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
7125 } else {
7126 Diag(Tok, diag::err_expected_comma_or_rsquare);
7127 }
7128
7129 SkipUntil(tok::r_square, tok::comma, tok::identifier,
7131 if (Tok.is(tok::comma))
7132 ConsumeToken();
7133 else if (Tok.isNot(tok::identifier))
7134 break;
7135 }
7136 }
7137
7138 if (isCXX11AttributeSpecifier())
7139 DiagnoseAndSkipCXX11Attributes();
7140
7141 if (Tok.isNot(tok::identifier)) {
7142 Diag(Tok, diag::err_expected) << tok::identifier;
7143 break;
7144 }
7145
7148 ConsumeToken();
7149
7150 ParsedAttributes Attrs(AttrFactory);
7151 if (isCXX11AttributeSpecifier()) {
7153 ? diag::warn_cxx23_compat_decl_attrs_on_binding
7154 : diag::ext_decl_attrs_on_binding);
7155 MaybeParseCXX11Attributes(Attrs);
7156 }
7157
7158 Bindings.push_back({II, Loc, std::move(Attrs)});
7159 }
7160
7161 if (Tok.isNot(tok::r_square))
7162 // We've already diagnosed a problem here.
7163 T.skipToEnd();
7164 else {
7165 // C++17 does not allow the identifier-list in a structured binding
7166 // to be empty.
7167 if (Bindings.empty())
7168 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
7169
7170 T.consumeClose();
7171 }
7172
7173 PA.Commit();
7174
7175 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
7176 T.getCloseLocation());
7177}
7178
7179/// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
7180/// only called before the identifier, so these are most likely just grouping
7181/// parens for precedence. If we find that these are actually function
7182/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
7183///
7184/// direct-declarator:
7185/// '(' declarator ')'
7186/// [GNU] '(' attributes declarator ')'
7187/// direct-declarator '(' parameter-type-list ')'
7188/// direct-declarator '(' identifier-list[opt] ')'
7189/// [GNU] direct-declarator '(' parameter-forward-declarations
7190/// parameter-type-list[opt] ')'
7191///
7192void Parser::ParseParenDeclarator(Declarator &D) {
7193 BalancedDelimiterTracker T(*this, tok::l_paren);
7194 T.consumeOpen();
7195
7196 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
7197
7198 // Eat any attributes before we look at whether this is a grouping or function
7199 // declarator paren. If this is a grouping paren, the attribute applies to
7200 // the type being built up, for example:
7201 // int (__attribute__(()) *x)(long y)
7202 // If this ends up not being a grouping paren, the attribute applies to the
7203 // first argument, for example:
7204 // int (__attribute__(()) int x)
7205 // In either case, we need to eat any attributes to be able to determine what
7206 // sort of paren this is.
7207 //
7208 ParsedAttributes attrs(AttrFactory);
7209 bool RequiresArg = false;
7210 if (Tok.is(tok::kw___attribute)) {
7211 ParseGNUAttributes(attrs);
7212
7213 // We require that the argument list (if this is a non-grouping paren) be
7214 // present even if the attribute list was empty.
7215 RequiresArg = true;
7216 }
7217
7218 // Eat any Microsoft extensions.
7219 ParseMicrosoftTypeAttributes(attrs);
7220
7221 // Eat any Borland extensions.
7222 if (Tok.is(tok::kw___pascal))
7223 ParseBorlandTypeAttributes(attrs);
7224
7225 // If we haven't past the identifier yet (or where the identifier would be
7226 // stored, if this is an abstract declarator), then this is probably just
7227 // grouping parens. However, if this could be an abstract-declarator, then
7228 // this could also be the start of function arguments (consider 'void()').
7229 bool isGrouping;
7230
7231 if (!D.mayOmitIdentifier()) {
7232 // If this can't be an abstract-declarator, this *must* be a grouping
7233 // paren, because we haven't seen the identifier yet.
7234 isGrouping = true;
7235 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
7236 (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
7237 NextToken().is(tok::r_paren)) || // C++ int(...)
7238 isDeclarationSpecifier(
7239 ImplicitTypenameContext::No) || // 'int(int)' is a function.
7240 isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
7241 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
7242 // considered to be a type, not a K&R identifier-list.
7243 isGrouping = false;
7244 } else {
7245 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
7246 isGrouping = true;
7247 }
7248
7249 // If this is a grouping paren, handle:
7250 // direct-declarator: '(' declarator ')'
7251 // direct-declarator: '(' attributes declarator ')'
7252 if (isGrouping) {
7253 SourceLocation EllipsisLoc = D.getEllipsisLoc();
7255
7256 bool hadGroupingParens = D.hasGroupingParens();
7257 D.setGroupingParens(true);
7258 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
7259 // Match the ')'.
7260 T.consumeClose();
7261 D.AddTypeInfo(
7262 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
7263 std::move(attrs), T.getCloseLocation());
7264
7265 D.setGroupingParens(hadGroupingParens);
7266
7267 // An ellipsis cannot be placed outside parentheses.
7268 if (EllipsisLoc.isValid())
7269 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
7270
7271 return;
7272 }
7273
7274 // Okay, if this wasn't a grouping paren, it must be the start of a function
7275 // argument list. Recognize that this declarator will never have an
7276 // identifier (and remember where it would have been), then call into
7277 // ParseFunctionDeclarator to handle of argument list.
7278 D.SetIdentifier(nullptr, Tok.getLocation());
7279
7280 // Enter function-declaration scope, limiting any declarators to the
7281 // function prototype scope, including parameter declarators.
7282 ParseScope PrototypeScope(this,
7286 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
7287 PrototypeScope.Exit();
7288}
7289
7290void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
7291 const Declarator &D, const DeclSpec &DS,
7292 std::optional<Sema::CXXThisScopeRAII> &ThisScope) {
7293 // C++11 [expr.prim.general]p3:
7294 // If a declaration declares a member function or member function
7295 // template of a class X, the expression this is a prvalue of type
7296 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
7297 // and the end of the function-definition, member-declarator, or
7298 // declarator.
7299 // FIXME: currently, "static" case isn't handled correctly.
7300 bool IsCXX11MemberFunction =
7301 getLangOpts().CPlusPlus11 &&
7306 D.getCXXScopeSpec().isValid() &&
7307 Actions.CurContext->isRecord());
7308 if (!IsCXX11MemberFunction)
7309 return;
7310
7313 Q.addConst();
7314 // FIXME: Collect C++ address spaces.
7315 // If there are multiple different address spaces, the source is invalid.
7316 // Carry on using the first addr space for the qualifiers of 'this'.
7317 // The diagnostic will be given later while creating the function
7318 // prototype for the method.
7319 if (getLangOpts().OpenCLCPlusPlus) {
7320 for (ParsedAttr &attr : DS.getAttributes()) {
7321 LangAS ASIdx = attr.asOpenCLLangAS();
7322 if (ASIdx != LangAS::Default) {
7323 Q.addAddressSpace(ASIdx);
7324 break;
7325 }
7326 }
7327 }
7328 ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
7329 IsCXX11MemberFunction);
7330}
7331
7332/// ParseFunctionDeclarator - We are after the identifier and have parsed the
7333/// declarator D up to a paren, which indicates that we are parsing function
7334/// arguments.
7335///
7336/// If FirstArgAttrs is non-null, then the caller parsed those attributes
7337/// immediately after the open paren - they will be applied to the DeclSpec
7338/// of the first parameter.
7339///
7340/// If RequiresArg is true, then the first argument of the function is required
7341/// to be present and required to not be an identifier list.
7342///
7343/// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
7344/// (C++11) ref-qualifier[opt], exception-specification[opt],
7345/// (C++11) attribute-specifier-seq[opt], (C++11) trailing-return-type[opt] and
7346/// (C++2a) the trailing requires-clause.
7347///
7348/// [C++11] exception-specification:
7349/// dynamic-exception-specification
7350/// noexcept-specification
7351///
7352void Parser::ParseFunctionDeclarator(Declarator &D,
7353 ParsedAttributes &FirstArgAttrs,
7354 BalancedDelimiterTracker &Tracker,
7355 bool IsAmbiguous,
7356 bool RequiresArg) {
7357 assert(getCurScope()->isFunctionPrototypeScope() &&
7358 "Should call from a Function scope");
7359 // lparen is already consumed!
7360 assert(D.isPastIdentifier() && "Should not call before identifier!");
7361
7362 // This should be true when the function has typed arguments.
7363 // Otherwise, it is treated as a K&R-style function.
7364 bool HasProto = false;
7365 // Build up an array of information about the parsed arguments.
7367 // Remember where we see an ellipsis, if any.
7368 SourceLocation EllipsisLoc;
7369
7370 DeclSpec DS(AttrFactory);
7371 bool RefQualifierIsLValueRef = true;
7372 SourceLocation RefQualifierLoc;
7374 SourceRange ESpecRange;
7375 SmallVector<ParsedType, 2> DynamicExceptions;
7376 SmallVector<SourceRange, 2> DynamicExceptionRanges;
7377 ExprResult NoexceptExpr;
7378 CachedTokens *ExceptionSpecTokens = nullptr;
7379 ParsedAttributes FnAttrs(AttrFactory);
7380 TypeResult TrailingReturnType;
7381 SourceLocation TrailingReturnTypeLoc;
7382
7383 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
7384 EndLoc is the end location for the function declarator.
7385 They differ for trailing return types. */
7386 SourceLocation StartLoc, LocalEndLoc, EndLoc;
7387 SourceLocation LParenLoc, RParenLoc;
7388 LParenLoc = Tracker.getOpenLocation();
7389 StartLoc = LParenLoc;
7390
7391 if (isFunctionDeclaratorIdentifierList()) {
7392 if (RequiresArg)
7393 Diag(Tok, diag::err_argument_required_after_attribute);
7394
7395 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
7396
7397 Tracker.consumeClose();
7398 RParenLoc = Tracker.getCloseLocation();
7399 LocalEndLoc = RParenLoc;
7400 EndLoc = RParenLoc;
7401
7402 // If there are attributes following the identifier list, parse them and
7403 // prohibit them.
7404 MaybeParseCXX11Attributes(FnAttrs);
7405 ProhibitAttributes(FnAttrs);
7406 } else {
7407 if (Tok.isNot(tok::r_paren))
7408 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
7409 else if (RequiresArg)
7410 Diag(Tok, diag::err_argument_required_after_attribute);
7411
7412 // OpenCL disallows functions without a prototype, but it doesn't enforce
7413 // strict prototypes as in C23 because it allows a function definition to
7414 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
7415 HasProto = ParamInfo.size() || getLangOpts().requiresStrictPrototypes() ||
7416 getLangOpts().OpenCL;
7417
7418 // If we have the closing ')', eat it.
7419 Tracker.consumeClose();
7420 RParenLoc = Tracker.getCloseLocation();
7421 LocalEndLoc = RParenLoc;
7422 EndLoc = RParenLoc;
7423
7424 if (getLangOpts().CPlusPlus) {
7425 // FIXME: Accept these components in any order, and produce fixits to
7426 // correct the order if the user gets it wrong. Ideally we should deal
7427 // with the pure-specifier in the same way.
7428
7429 // Parse cv-qualifier-seq[opt].
7430 ParseTypeQualifierListOpt(
7431 DS, AR_NoAttributesParsed,
7432 /*AtomicAllowed*/ false,
7433 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
7434 Actions.CodeCompletion().CodeCompleteFunctionQualifiers(DS, D);
7435 }));
7436 if (!DS.getSourceRange().getEnd().isInvalid()) {
7437 EndLoc = DS.getSourceRange().getEnd();
7438 }
7439
7440 // Parse ref-qualifier[opt].
7441 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
7442 EndLoc = RefQualifierLoc;
7443
7444 std::optional<Sema::CXXThisScopeRAII> ThisScope;
7445 InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
7446
7447 // C++ [class.mem.general]p8:
7448 // A complete-class context of a class (template) is a
7449 // - function body,
7450 // - default argument,
7451 // - default template argument,
7452 // - noexcept-specifier, or
7453 // - default member initializer
7454 // within the member-specification of the class or class template.
7455 //
7456 // Parse exception-specification[opt]. If we are in the
7457 // member-specification of a class or class template, this is a
7458 // complete-class context and parsing of the noexcept-specifier should be
7459 // delayed (even if this is a friend declaration).
7460 bool Delayed = D.getContext() == DeclaratorContext::Member &&
7462 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
7463 GetLookAheadToken(0).is(tok::kw_noexcept) &&
7464 GetLookAheadToken(1).is(tok::l_paren) &&
7465 GetLookAheadToken(2).is(tok::kw_noexcept) &&
7466 GetLookAheadToken(3).is(tok::l_paren) &&
7467 GetLookAheadToken(4).is(tok::identifier) &&
7468 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
7469 // HACK: We've got an exception-specification
7470 // noexcept(noexcept(swap(...)))
7471 // or
7472 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
7473 // on a 'swap' member function. This is a libstdc++ bug; the lookup
7474 // for 'swap' will only find the function we're currently declaring,
7475 // whereas it expects to find a non-member swap through ADL. Turn off
7476 // delayed parsing to give it a chance to find what it expects.
7477 Delayed = false;
7478 }
7479 ESpecType = tryParseExceptionSpecification(Delayed,
7480 ESpecRange,
7481 DynamicExceptions,
7482 DynamicExceptionRanges,
7483 NoexceptExpr,
7484 ExceptionSpecTokens);
7485 if (ESpecType != EST_None)
7486 EndLoc = ESpecRange.getEnd();
7487
7488 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
7489 // after the exception-specification.
7490 MaybeParseCXX11Attributes(FnAttrs);
7491
7492 // Parse trailing-return-type[opt].
7493 LocalEndLoc = EndLoc;
7494 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
7495 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
7497 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
7498 LocalEndLoc = Tok.getLocation();
7500 TrailingReturnType =
7501 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
7502 TrailingReturnTypeLoc = Range.getBegin();
7503 EndLoc = Range.getEnd();
7504 }
7505 } else {
7506 MaybeParseCXX11Attributes(FnAttrs);
7507 }
7508 }
7509
7510 // Collect non-parameter declarations from the prototype if this is a function
7511 // declaration. They will be moved into the scope of the function. Only do
7512 // this in C and not C++, where the decls will continue to live in the
7513 // surrounding context.
7514 SmallVector<NamedDecl *, 0> DeclsInPrototype;
7515 if (getCurScope()->isFunctionDeclarationScope() && !getLangOpts().CPlusPlus) {
7516 for (Decl *D : getCurScope()->decls()) {
7517 NamedDecl *ND = dyn_cast<NamedDecl>(D);
7518 if (!ND || isa<ParmVarDecl>(ND))
7519 continue;
7520 DeclsInPrototype.push_back(ND);
7521 }
7522 // Sort DeclsInPrototype based on raw encoding of the source location.
7523 // Scope::decls() is iterating over a SmallPtrSet so sort the Decls before
7524 // moving to DeclContext. This provides a stable ordering for traversing
7525 // Decls in DeclContext, which is important for tasks like ASTWriter for
7526 // deterministic output.
7527 llvm::sort(DeclsInPrototype, [](Decl *D1, Decl *D2) {
7528 return D1->getLocation().getRawEncoding() <
7530 });
7531 }
7532
7533 // Remember that we parsed a function type, and remember the attributes.
7535 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
7536 ParamInfo.size(), EllipsisLoc, RParenLoc,
7537 RefQualifierIsLValueRef, RefQualifierLoc,
7538 /*MutableLoc=*/SourceLocation(),
7539 ESpecType, ESpecRange, DynamicExceptions.data(),
7540 DynamicExceptionRanges.data(), DynamicExceptions.size(),
7541 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
7542 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
7543 LocalEndLoc, D, TrailingReturnType, TrailingReturnTypeLoc,
7544 &DS),
7545 std::move(FnAttrs), EndLoc);
7546}
7547
7548/// ParseRefQualifier - Parses a member function ref-qualifier. Returns
7549/// true if a ref-qualifier is found.
7550bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
7551 SourceLocation &RefQualifierLoc) {
7552 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
7554 diag::warn_cxx98_compat_ref_qualifier :
7555 diag::ext_ref_qualifier);
7556
7557 RefQualifierIsLValueRef = Tok.is(tok::amp);
7558 RefQualifierLoc = ConsumeToken();
7559 return true;
7560 }
7561 return false;
7562}
7563
7564/// isFunctionDeclaratorIdentifierList - This parameter list may have an
7565/// identifier list form for a K&R-style function: void foo(a,b,c)
7566///
7567/// Note that identifier-lists are only allowed for normal declarators, not for
7568/// abstract-declarators.
7569bool Parser::isFunctionDeclaratorIdentifierList() {
7571 && Tok.is(tok::identifier)
7572 && !TryAltiVecVectorToken()
7573 // K&R identifier lists can't have typedefs as identifiers, per C99
7574 // 6.7.5.3p11.
7575 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
7576 // Identifier lists follow a really simple grammar: the identifiers can
7577 // be followed *only* by a ", identifier" or ")". However, K&R
7578 // identifier lists are really rare in the brave new modern world, and
7579 // it is very common for someone to typo a type in a non-K&R style
7580 // list. If we are presented with something like: "void foo(intptr x,
7581 // float y)", we don't want to start parsing the function declarator as
7582 // though it is a K&R style declarator just because intptr is an
7583 // invalid type.
7584 //
7585 // To handle this, we check to see if the token after the first
7586 // identifier is a "," or ")". Only then do we parse it as an
7587 // identifier list.
7588 && (!Tok.is(tok::eof) &&
7589 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
7590}
7591
7592/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
7593/// we found a K&R-style identifier list instead of a typed parameter list.
7594///
7595/// After returning, ParamInfo will hold the parsed parameters.
7596///
7597/// identifier-list: [C99 6.7.5]
7598/// identifier
7599/// identifier-list ',' identifier
7600///
7601void Parser::ParseFunctionDeclaratorIdentifierList(
7602 Declarator &D,
7604 // We should never reach this point in C23 or C++.
7605 assert(!getLangOpts().requiresStrictPrototypes() &&
7606 "Cannot parse an identifier list in C23 or C++");
7607
7608 // If there was no identifier specified for the declarator, either we are in
7609 // an abstract-declarator, or we are in a parameter declarator which was found
7610 // to be abstract. In abstract-declarators, identifier lists are not valid:
7611 // diagnose this.
7612 if (!D.getIdentifier())
7613 Diag(Tok, diag::ext_ident_list_in_param);
7614
7615 // Maintain an efficient lookup of params we have seen so far.
7616 llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
7617
7618 do {
7619 // If this isn't an identifier, report the error and skip until ')'.
7620 if (Tok.isNot(tok::identifier)) {
7621 Diag(Tok, diag::err_expected) << tok::identifier;
7622 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
7623 // Forget we parsed anything.
7624 ParamInfo.clear();
7625 return;
7626 }
7627
7628 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
7629
7630 // Reject 'typedef int y; int test(x, y)', but continue parsing.
7631 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
7632 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
7633
7634 // Verify that the argument identifier has not already been mentioned.
7635 if (!ParamsSoFar.insert(ParmII).second) {
7636 Diag(Tok, diag::err_param_redefinition) << ParmII;
7637 } else {
7638 // Remember this identifier in ParamInfo.
7639 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7640 Tok.getLocation(),
7641 nullptr));
7642 }
7643
7644 // Eat the identifier.
7645 ConsumeToken();
7646 // The list continues if we see a comma.
7647 } while (TryConsumeToken(tok::comma));
7648}
7649
7650/// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
7651/// after the opening parenthesis. This function will not parse a K&R-style
7652/// identifier list.
7653///
7654/// DeclContext is the context of the declarator being parsed. If FirstArgAttrs
7655/// is non-null, then the caller parsed those attributes immediately after the
7656/// open paren - they will be applied to the DeclSpec of the first parameter.
7657///
7658/// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
7659/// be the location of the ellipsis, if any was parsed.
7660///
7661/// parameter-type-list: [C99 6.7.5]
7662/// parameter-list
7663/// parameter-list ',' '...'
7664/// [C++] parameter-list '...'
7665///
7666/// parameter-list: [C99 6.7.5]
7667/// parameter-declaration
7668/// parameter-list ',' parameter-declaration
7669///
7670/// parameter-declaration: [C99 6.7.5]
7671/// declaration-specifiers declarator
7672/// [C++] declaration-specifiers declarator '=' assignment-expression
7673/// [C++11] initializer-clause
7674/// [GNU] declaration-specifiers declarator attributes
7675/// declaration-specifiers abstract-declarator[opt]
7676/// [C++] declaration-specifiers abstract-declarator[opt]
7677/// '=' assignment-expression
7678/// [GNU] declaration-specifiers abstract-declarator[opt] attributes
7679/// [C++11] attribute-specifier-seq parameter-declaration
7680/// [C++2b] attribute-specifier-seq 'this' parameter-declaration
7681///
7682void Parser::ParseParameterDeclarationClause(
7683 DeclaratorContext DeclaratorCtx, ParsedAttributes &FirstArgAttrs,
7685 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration) {
7686
7687 // Avoid exceeding the maximum function scope depth.
7688 // See https://bugs.llvm.org/show_bug.cgi?id=19607
7689 // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
7690 // getFunctionPrototypeDepth() - 1.
7691 if (getCurScope()->getFunctionPrototypeDepth() - 1 >
7693 Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
7695 cutOffParsing();
7696 return;
7697 }
7698
7699 // C++2a [temp.res]p5
7700 // A qualified-id is assumed to name a type if
7701 // - [...]
7702 // - it is a decl-specifier of the decl-specifier-seq of a
7703 // - [...]
7704 // - parameter-declaration in a member-declaration [...]
7705 // - parameter-declaration in a declarator of a function or function
7706 // template declaration whose declarator-id is qualified [...]
7707 // - parameter-declaration in a lambda-declarator [...]
7708 auto AllowImplicitTypename = ImplicitTypenameContext::No;
7709 if (DeclaratorCtx == DeclaratorContext::Member ||
7710 DeclaratorCtx == DeclaratorContext::LambdaExpr ||
7711 DeclaratorCtx == DeclaratorContext::RequiresExpr ||
7712 IsACXXFunctionDeclaration) {
7713 AllowImplicitTypename = ImplicitTypenameContext::Yes;
7714 }
7715
7716 do {
7717 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
7718 // before deciding this was a parameter-declaration-clause.
7719 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
7720 break;
7721
7722 // Parse the declaration-specifiers.
7723 // Just use the ParsingDeclaration "scope" of the declarator.
7724 DeclSpec DS(AttrFactory);
7725
7726 ParsedAttributes ArgDeclAttrs(AttrFactory);
7727 ParsedAttributes ArgDeclSpecAttrs(AttrFactory);
7728
7729 if (FirstArgAttrs.Range.isValid()) {
7730 // If the caller parsed attributes for the first argument, add them now.
7731 // Take them so that we only apply the attributes to the first parameter.
7732 // We have already started parsing the decl-specifier sequence, so don't
7733 // parse any parameter-declaration pieces that precede it.
7734 ArgDeclSpecAttrs.takeAllFrom(FirstArgAttrs);
7735 } else {
7736 // Parse any C++11 attributes.
7737 MaybeParseCXX11Attributes(ArgDeclAttrs);
7738
7739 // Skip any Microsoft attributes before a param.
7740 MaybeParseMicrosoftAttributes(ArgDeclSpecAttrs);
7741 }
7742
7743 SourceLocation DSStart = Tok.getLocation();
7744
7745 // Parse a C++23 Explicit Object Parameter
7746 // We do that in all language modes to produce a better diagnostic.
7747 SourceLocation ThisLoc;
7748 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_this)) {
7749 ThisLoc = ConsumeToken();
7750 // C++23 [dcl.fct]p6:
7751 // An explicit-object-parameter-declaration is a parameter-declaration
7752 // with a this specifier. An explicit-object-parameter-declaration
7753 // shall appear only as the first parameter-declaration of a
7754 // parameter-declaration-list of either:
7755 // - a member-declarator that declares a member function, or
7756 // - a lambda-declarator.
7757 //
7758 // The parameter-declaration-list of a requires-expression is not such
7759 // a context.
7760 if (DeclaratorCtx == DeclaratorContext::RequiresExpr)
7761 Diag(ThisLoc, diag::err_requires_expr_explicit_object_parameter);
7762 }
7763
7764 ParsedTemplateInfo TemplateInfo;
7765 ParseDeclarationSpecifiers(DS, TemplateInfo, AS_none,
7766 DeclSpecContext::DSC_normal,
7767 /*LateAttrs=*/nullptr, AllowImplicitTypename);
7768
7769 DS.takeAttributesFrom(ArgDeclSpecAttrs);
7770
7771 // Parse the declarator. This is "PrototypeContext" or
7772 // "LambdaExprParameterContext", because we must accept either
7773 // 'declarator' or 'abstract-declarator' here.
7774 Declarator ParmDeclarator(DS, ArgDeclAttrs,
7775 DeclaratorCtx == DeclaratorContext::RequiresExpr
7777 : DeclaratorCtx == DeclaratorContext::LambdaExpr
7780 ParseDeclarator(ParmDeclarator);
7781
7782 if (ThisLoc.isValid())
7783 ParmDeclarator.SetRangeBegin(ThisLoc);
7784
7785 // Parse GNU attributes, if present.
7786 MaybeParseGNUAttributes(ParmDeclarator);
7787 if (getLangOpts().HLSL)
7788 MaybeParseHLSLAnnotations(DS.getAttributes());
7789
7790 if (Tok.is(tok::kw_requires)) {
7791 // User tried to define a requires clause in a parameter declaration,
7792 // which is surely not a function declaration.
7793 // void f(int (*g)(int, int) requires true);
7794 Diag(Tok,
7795 diag::err_requires_clause_on_declarator_not_declaring_a_function);
7796 ConsumeToken();
7798 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
7799 }
7800
7801 // Remember this parsed parameter in ParamInfo.
7802 const IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
7803
7804 // DefArgToks is used when the parsing of default arguments needs
7805 // to be delayed.
7806 std::unique_ptr<CachedTokens> DefArgToks;
7807
7808 // If no parameter was specified, verify that *something* was specified,
7809 // otherwise we have a missing type and identifier.
7810 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
7811 ParmDeclarator.getNumTypeObjects() == 0) {
7812 // Completely missing, emit error.
7813 Diag(DSStart, diag::err_missing_param);
7814 } else {
7815 // Otherwise, we have something. Add it and let semantic analysis try
7816 // to grok it and add the result to the ParamInfo we are building.
7817
7818 // Last chance to recover from a misplaced ellipsis in an attempted
7819 // parameter pack declaration.
7820 if (Tok.is(tok::ellipsis) &&
7821 (NextToken().isNot(tok::r_paren) ||
7822 (!ParmDeclarator.getEllipsisLoc().isValid() &&
7824 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
7825 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
7826
7827 // Now we are at the point where declarator parsing is finished.
7828 //
7829 // Try to catch keywords in place of the identifier in a declarator, and
7830 // in particular the common case where:
7831 // 1 identifier comes at the end of the declarator
7832 // 2 if the identifier is dropped, the declarator is valid but anonymous
7833 // (no identifier)
7834 // 3 declarator parsing succeeds, and then we have a trailing keyword,
7835 // which is never valid in a param list (e.g. missing a ',')
7836 // And we can't handle this in ParseDeclarator because in general keywords
7837 // may be allowed to follow the declarator. (And in some cases there'd be
7838 // better recovery like inserting punctuation). ParseDeclarator is just
7839 // treating this as an anonymous parameter, and fortunately at this point
7840 // we've already almost done that.
7841 //
7842 // We care about case 1) where the declarator type should be known, and
7843 // the identifier should be null.
7844 if (!ParmDeclarator.isInvalidType() && !ParmDeclarator.hasName() &&
7845 Tok.isNot(tok::raw_identifier) && !Tok.isAnnotation() &&
7846 Tok.getIdentifierInfo() &&
7848 Diag(Tok, diag::err_keyword_as_parameter) << PP.getSpelling(Tok);
7849 // Consume the keyword.
7850 ConsumeToken();
7851 }
7852 // Inform the actions module about the parameter declarator, so it gets
7853 // added to the current scope.
7854 Decl *Param =
7855 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator, ThisLoc);
7856 // Parse the default argument, if any. We parse the default
7857 // arguments in all dialects; the semantic analysis in
7858 // ActOnParamDefaultArgument will reject the default argument in
7859 // C.
7860 if (Tok.is(tok::equal)) {
7861 SourceLocation EqualLoc = Tok.getLocation();
7862
7863 // Parse the default argument
7864 if (DeclaratorCtx == DeclaratorContext::Member) {
7865 // If we're inside a class definition, cache the tokens
7866 // corresponding to the default argument. We'll actually parse
7867 // them when we see the end of the class definition.
7868 DefArgToks.reset(new CachedTokens);
7869
7870 SourceLocation ArgStartLoc = NextToken().getLocation();
7871 ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument);
7872 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
7873 ArgStartLoc);
7874 } else {
7875 // Consume the '='.
7876 ConsumeToken();
7877
7878 // The argument isn't actually potentially evaluated unless it is
7879 // used.
7881 Actions,
7883 Param);
7884
7885 ExprResult DefArgResult;
7886 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
7887 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
7888 DefArgResult = ParseBraceInitializer();
7889 } else {
7890 if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
7891 Diag(Tok, diag::err_stmt_expr_in_default_arg) << 0;
7892 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
7893 /*DefaultArg=*/nullptr);
7894 // Skip the statement expression and continue parsing
7895 SkipUntil(tok::comma, StopBeforeMatch);
7896 continue;
7897 }
7898 DefArgResult = ParseAssignmentExpression();
7899 }
7900 DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
7901 if (DefArgResult.isInvalid()) {
7902 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
7903 /*DefaultArg=*/nullptr);
7904 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
7905 } else {
7906 // Inform the actions module about the default argument
7907 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
7908 DefArgResult.get());
7909 }
7910 }
7911 }
7912
7913 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7914 ParmDeclarator.getIdentifierLoc(),
7915 Param, std::move(DefArgToks)));
7916 }
7917
7918 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
7919 if (!getLangOpts().CPlusPlus) {
7920 // We have ellipsis without a preceding ',', which is ill-formed
7921 // in C. Complain and provide the fix.
7922 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
7923 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7924 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
7925 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
7926 // It looks like this was supposed to be a parameter pack. Warn and
7927 // point out where the ellipsis should have gone.
7928 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
7929 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
7930 << ParmEllipsis.isValid() << ParmEllipsis;
7931 if (ParmEllipsis.isValid()) {
7932 Diag(ParmEllipsis,
7933 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
7934 } else {
7935 Diag(ParmDeclarator.getIdentifierLoc(),
7936 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
7937 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
7938 "...")
7939 << !ParmDeclarator.hasName();
7940 }
7941 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
7942 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7943 }
7944
7945 // We can't have any more parameters after an ellipsis.
7946 break;
7947 }
7948
7949 // If the next token is a comma, consume it and keep reading arguments.
7950 } while (TryConsumeToken(tok::comma));
7951}
7952
7953/// [C90] direct-declarator '[' constant-expression[opt] ']'
7954/// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
7955/// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
7956/// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
7957/// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
7958/// [C++11] direct-declarator '[' constant-expression[opt] ']'
7959/// attribute-specifier-seq[opt]
7960void Parser::ParseBracketDeclarator(Declarator &D) {
7961 if (CheckProhibitedCXX11Attribute())
7962 return;
7963
7964 BalancedDelimiterTracker T(*this, tok::l_square);
7965 T.consumeOpen();
7966
7967 // C array syntax has many features, but by-far the most common is [] and [4].
7968 // This code does a fast path to handle some of the most obvious cases.
7969 if (Tok.getKind() == tok::r_square) {
7970 T.consumeClose();
7971 ParsedAttributes attrs(AttrFactory);
7972 MaybeParseCXX11Attributes(attrs);
7973
7974 // Remember that we parsed the empty array type.
7975 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
7976 T.getOpenLocation(),
7977 T.getCloseLocation()),
7978 std::move(attrs), T.getCloseLocation());
7979 return;
7980 } else if (Tok.getKind() == tok::numeric_constant &&
7981 GetLookAheadToken(1).is(tok::r_square)) {
7982 // [4] is very common. Parse the numeric constant expression.
7983 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
7984 ConsumeToken();
7985
7986 T.consumeClose();
7987 ParsedAttributes attrs(AttrFactory);
7988 MaybeParseCXX11Attributes(attrs);
7989
7990 // Remember that we parsed a array type, and remember its features.
7991 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
7992 T.getOpenLocation(),
7993 T.getCloseLocation()),
7994 std::move(attrs), T.getCloseLocation());
7995 return;
7996 } else if (Tok.getKind() == tok::code_completion) {
7997 cutOffParsing();
7999 return;
8000 }
8001
8002 // If valid, this location is the position where we read the 'static' keyword.
8003 SourceLocation StaticLoc;
8004 TryConsumeToken(tok::kw_static, StaticLoc);
8005
8006 // If there is a type-qualifier-list, read it now.
8007 // Type qualifiers in an array subscript are a C99 feature.
8008 DeclSpec DS(AttrFactory);
8009 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
8010
8011 // If we haven't already read 'static', check to see if there is one after the
8012 // type-qualifier-list.
8013 if (!StaticLoc.isValid())
8014 TryConsumeToken(tok::kw_static, StaticLoc);
8015
8016 // Handle "direct-declarator [ type-qual-list[opt] * ]".
8017 bool isStar = false;
8018 ExprResult NumElements;
8019
8020 // Handle the case where we have '[*]' as the array size. However, a leading
8021 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
8022 // the token after the star is a ']'. Since stars in arrays are
8023 // infrequent, use of lookahead is not costly here.
8024 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
8025 ConsumeToken(); // Eat the '*'.
8026
8027 if (StaticLoc.isValid()) {
8028 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
8029 StaticLoc = SourceLocation(); // Drop the static.
8030 }
8031 isStar = true;
8032 } else if (Tok.isNot(tok::r_square)) {
8033 // Note, in C89, this production uses the constant-expr production instead
8034 // of assignment-expr. The only difference is that assignment-expr allows
8035 // things like '=' and '*='. Sema rejects these in C89 mode because they
8036 // are not i-c-e's, so we don't need to distinguish between the two here.
8037
8038 // Parse the constant-expression or assignment-expression now (depending
8039 // on dialect).
8040 if (getLangOpts().CPlusPlus) {
8041 NumElements = ParseArrayBoundExpression();
8042 } else {
8045 NumElements =
8047 }
8048 } else {
8049 if (StaticLoc.isValid()) {
8050 Diag(StaticLoc, diag::err_unspecified_size_with_static);
8051 StaticLoc = SourceLocation(); // Drop the static.
8052 }
8053 }
8054
8055 // If there was an error parsing the assignment-expression, recover.
8056 if (NumElements.isInvalid()) {
8057 D.setInvalidType(true);
8058 // If the expression was invalid, skip it.
8059 SkipUntil(tok::r_square, StopAtSemi);
8060 return;
8061 }
8062
8063 T.consumeClose();
8064
8065 MaybeParseCXX11Attributes(DS.getAttributes());
8066
8067 // Remember that we parsed a array type, and remember its features.
8068 D.AddTypeInfo(
8070 isStar, NumElements.get(), T.getOpenLocation(),
8071 T.getCloseLocation()),
8072 std::move(DS.getAttributes()), T.getCloseLocation());
8073}
8074
8075/// Diagnose brackets before an identifier.
8076void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
8077 assert(Tok.is(tok::l_square) && "Missing opening bracket");
8078 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
8079
8080 SourceLocation StartBracketLoc = Tok.getLocation();
8082 D.getContext());
8083
8084 while (Tok.is(tok::l_square)) {
8085 ParseBracketDeclarator(TempDeclarator);
8086 }
8087
8088 // Stuff the location of the start of the brackets into the Declarator.
8089 // The diagnostics from ParseDirectDeclarator will make more sense if
8090 // they use this location instead.
8091 if (Tok.is(tok::semi))
8092 D.getName().EndLocation = StartBracketLoc;
8093
8094 SourceLocation SuggestParenLoc = Tok.getLocation();
8095
8096 // Now that the brackets are removed, try parsing the declarator again.
8097 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
8098
8099 // Something went wrong parsing the brackets, in which case,
8100 // ParseBracketDeclarator has emitted an error, and we don't need to emit
8101 // one here.
8102 if (TempDeclarator.getNumTypeObjects() == 0)
8103 return;
8104
8105 // Determine if parens will need to be suggested in the diagnostic.
8106 bool NeedParens = false;
8107 if (D.getNumTypeObjects() != 0) {
8108 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
8114 NeedParens = true;
8115 break;
8119 break;
8120 }
8121 }
8122
8123 if (NeedParens) {
8124 // Create a DeclaratorChunk for the inserted parens.
8126 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
8127 SourceLocation());
8128 }
8129
8130 // Adding back the bracket info to the end of the Declarator.
8131 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
8132 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
8133 D.AddTypeInfo(Chunk, TempDeclarator.getAttributePool(), SourceLocation());
8134 }
8135
8136 // The missing identifier would have been diagnosed in ParseDirectDeclarator.
8137 // If parentheses are required, always suggest them.
8138 if (!D.getIdentifier() && !NeedParens)
8139 return;
8140
8141 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
8142
8143 // Generate the move bracket error message.
8144 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
8146
8147 if (NeedParens) {
8148 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
8149 << getLangOpts().CPlusPlus
8150 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
8151 << FixItHint::CreateInsertion(EndLoc, ")")
8153 EndLoc, CharSourceRange(BracketRange, true))
8154 << FixItHint::CreateRemoval(BracketRange);
8155 } else {
8156 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
8157 << getLangOpts().CPlusPlus
8159 EndLoc, CharSourceRange(BracketRange, true))
8160 << FixItHint::CreateRemoval(BracketRange);
8161 }
8162}
8163
8164/// [GNU] typeof-specifier:
8165/// typeof ( expressions )
8166/// typeof ( type-name )
8167/// [GNU/C++] typeof unary-expression
8168/// [C23] typeof-specifier:
8169/// typeof '(' typeof-specifier-argument ')'
8170/// typeof_unqual '(' typeof-specifier-argument ')'
8171///
8172/// typeof-specifier-argument:
8173/// expression
8174/// type-name
8175///
8176void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
8177 assert(Tok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
8178 "Not a typeof specifier");
8179
8180 bool IsUnqual = Tok.is(tok::kw_typeof_unqual);
8181 const IdentifierInfo *II = Tok.getIdentifierInfo();
8182 if (getLangOpts().C23 && !II->getName().starts_with("__"))
8183 Diag(Tok.getLocation(), diag::warn_c23_compat_keyword) << Tok.getName();
8184
8185 Token OpTok = Tok;
8186 SourceLocation StartLoc = ConsumeToken();
8187 bool HasParens = Tok.is(tok::l_paren);
8188
8192
8193 bool isCastExpr;
8194 ParsedType CastTy;
8195 SourceRange CastRange;
8197 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
8198 if (HasParens)
8199 DS.setTypeArgumentRange(CastRange);
8200
8201 if (CastRange.getEnd().isInvalid())
8202 // FIXME: Not accurate, the range gets one token more than it should.
8203 DS.SetRangeEnd(Tok.getLocation());
8204 else
8205 DS.SetRangeEnd(CastRange.getEnd());
8206
8207 if (isCastExpr) {
8208 if (!CastTy) {
8209 DS.SetTypeSpecError();
8210 return;
8211 }
8212
8213 const char *PrevSpec = nullptr;
8214 unsigned DiagID;
8215 // Check for duplicate type specifiers (e.g. "int typeof(int)").
8218 StartLoc, PrevSpec,
8219 DiagID, CastTy,
8220 Actions.getASTContext().getPrintingPolicy()))
8221 Diag(StartLoc, DiagID) << PrevSpec;
8222 return;
8223 }
8224
8225 // If we get here, the operand to the typeof was an expression.
8226 if (Operand.isInvalid()) {
8227 DS.SetTypeSpecError();
8228 return;
8229 }
8230
8231 // We might need to transform the operand if it is potentially evaluated.
8233 if (Operand.isInvalid()) {
8234 DS.SetTypeSpecError();
8235 return;
8236 }
8237
8238 const char *PrevSpec = nullptr;
8239 unsigned DiagID;
8240 // Check for duplicate type specifiers (e.g. "int typeof(int)").
8243 StartLoc, PrevSpec,
8244 DiagID, Operand.get(),
8245 Actions.getASTContext().getPrintingPolicy()))
8246 Diag(StartLoc, DiagID) << PrevSpec;
8247}
8248
8249/// [C11] atomic-specifier:
8250/// _Atomic ( type-name )
8251///
8252void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
8253 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
8254 "Not an atomic specifier");
8255
8256 SourceLocation StartLoc = ConsumeToken();
8257 BalancedDelimiterTracker T(*this, tok::l_paren);
8258 if (T.consumeOpen())
8259 return;
8260
8262 if (Result.isInvalid()) {
8263 SkipUntil(tok::r_paren, StopAtSemi);
8264 return;
8265 }
8266
8267 // Match the ')'
8268 T.consumeClose();
8269
8270 if (T.getCloseLocation().isInvalid())
8271 return;
8272
8273 DS.setTypeArgumentRange(T.getRange());
8274 DS.SetRangeEnd(T.getCloseLocation());
8275
8276 const char *PrevSpec = nullptr;
8277 unsigned DiagID;
8278 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
8279 DiagID, Result.get(),
8280 Actions.getASTContext().getPrintingPolicy()))
8281 Diag(StartLoc, DiagID) << PrevSpec;
8282}
8283
8284/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
8285/// from TryAltiVecVectorToken.
8286bool Parser::TryAltiVecVectorTokenOutOfLine() {
8287 Token Next = NextToken();
8288 switch (Next.getKind()) {
8289 default: return false;
8290 case tok::kw_short:
8291 case tok::kw_long:
8292 case tok::kw_signed:
8293 case tok::kw_unsigned:
8294 case tok::kw_void:
8295 case tok::kw_char:
8296 case tok::kw_int:
8297 case tok::kw_float:
8298 case tok::kw_double:
8299 case tok::kw_bool:
8300 case tok::kw__Bool:
8301 case tok::kw___bool:
8302 case tok::kw___pixel:
8303 Tok.setKind(tok::kw___vector);
8304 return true;
8305 case tok::identifier:
8306 if (Next.getIdentifierInfo() == Ident_pixel) {
8307 Tok.setKind(tok::kw___vector);
8308 return true;
8309 }
8310 if (Next.getIdentifierInfo() == Ident_bool ||
8311 Next.getIdentifierInfo() == Ident_Bool) {
8312 Tok.setKind(tok::kw___vector);
8313 return true;
8314 }
8315 return false;
8316 }
8317}
8318
8319bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
8320 const char *&PrevSpec, unsigned &DiagID,
8321 bool &isInvalid) {
8322 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
8323 if (Tok.getIdentifierInfo() == Ident_vector) {
8324 Token Next = NextToken();
8325 switch (Next.getKind()) {
8326 case tok::kw_short:
8327 case tok::kw_long:
8328 case tok::kw_signed:
8329 case tok::kw_unsigned:
8330 case tok::kw_void:
8331 case tok::kw_char:
8332 case tok::kw_int:
8333 case tok::kw_float:
8334 case tok::kw_double:
8335 case tok::kw_bool:
8336 case tok::kw__Bool:
8337 case tok::kw___bool:
8338 case tok::kw___pixel:
8339 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
8340 return true;
8341 case tok::identifier:
8342 if (Next.getIdentifierInfo() == Ident_pixel) {
8343 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
8344 return true;
8345 }
8346 if (Next.getIdentifierInfo() == Ident_bool ||
8347 Next.getIdentifierInfo() == Ident_Bool) {
8348 isInvalid =
8349 DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
8350 return true;
8351 }
8352 break;
8353 default:
8354 break;
8355 }
8356 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
8357 DS.isTypeAltiVecVector()) {
8358 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
8359 return true;
8360 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
8361 DS.isTypeAltiVecVector()) {
8362 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
8363 return true;
8364 }
8365 return false;
8366}
8367
8368TypeResult Parser::ParseTypeFromString(StringRef TypeStr, StringRef Context,
8369 SourceLocation IncludeLoc) {
8370 // Consume (unexpanded) tokens up to the end-of-directive.
8371 SmallVector<Token, 4> Tokens;
8372 {
8373 // Create a new buffer from which we will parse the type.
8374 auto &SourceMgr = PP.getSourceManager();
8375 FileID FID = SourceMgr.createFileID(
8376 llvm::MemoryBuffer::getMemBufferCopy(TypeStr, Context), SrcMgr::C_User,
8377 0, 0, IncludeLoc);
8378
8379 // Form a new lexer that references the buffer.
8380 Lexer L(FID, SourceMgr.getBufferOrFake(FID), PP);
8381 L.setParsingPreprocessorDirective(true);
8382
8383 // Lex the tokens from that buffer.
8384 Token Tok;
8385 do {
8386 L.Lex(Tok);
8387 Tokens.push_back(Tok);
8388 } while (Tok.isNot(tok::eod));
8389 }
8390
8391 // Replace the "eod" token with an "eof" token identifying the end of
8392 // the provided string.
8393 Token &EndToken = Tokens.back();
8394 EndToken.startToken();
8395 EndToken.setKind(tok::eof);
8396 EndToken.setLocation(Tok.getLocation());
8397 EndToken.setEofData(TypeStr.data());
8398
8399 // Add the current token back.
8400 Tokens.push_back(Tok);
8401
8402 // Enter the tokens into the token stream.
8403 PP.EnterTokenStream(Tokens, /*DisableMacroExpansion=*/false,
8404 /*IsReinject=*/false);
8405
8406 // Consume the current token so that we'll start parsing the tokens we
8407 // added to the stream.
8409
8410 // Enter a new scope.
8411 ParseScope LocalScope(this, 0);
8412
8413 // Parse the type.
8414 TypeResult Result = ParseTypeName(nullptr);
8415
8416 // Check if we parsed the whole thing.
8417 if (Result.isUsable() &&
8418 (Tok.isNot(tok::eof) || Tok.getEofData() != TypeStr.data())) {
8419 Diag(Tok.getLocation(), diag::err_type_unparsed);
8420 }
8421
8422 // There could be leftover tokens (e.g. because of an error).
8423 // Skip through until we reach the 'end of directive' token.
8424 while (Tok.isNot(tok::eof))
8426
8427 // Consume the end token.
8428 if (Tok.is(tok::eof) && Tok.getEofData() == TypeStr.data())
8430 return Result;
8431}
8432
8433void Parser::DiagnoseBitIntUse(const Token &Tok) {
8434 // If the token is for _ExtInt, diagnose it as being deprecated. Otherwise,
8435 // the token is about _BitInt and gets (potentially) diagnosed as use of an
8436 // extension.
8437 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
8438 "expected either an _ExtInt or _BitInt token!");
8439
8441 if (Tok.is(tok::kw__ExtInt)) {
8442 Diag(Loc, diag::warn_ext_int_deprecated)
8443 << FixItHint::CreateReplacement(Loc, "_BitInt");
8444 } else {
8445 // In C23 mode, diagnose that the use is not compatible with pre-C23 modes.
8446 // Otherwise, diagnose that the use is a Clang extension.
8447 if (getLangOpts().C23)
8448 Diag(Loc, diag::warn_c23_compat_keyword) << Tok.getName();
8449 else
8450 Diag(Loc, diag::ext_bit_int) << getLangOpts().CPlusPlus;
8451 }
8452}
Defines the clang::ASTContext interface.
StringRef P
Provides definitions for the various language-specific address spaces.
static StringRef normalizeAttrName(const IdentifierInfo *Name, StringRef NormalizedScopeName, AttributeCommonInfo::Syntax SyntaxUsed)
Definition: Attributes.cpp:98
#define SM(sm)
Definition: Cuda.cpp:83
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1125
Defines the C++ template declaration subclasses.
#define X(type, name)
Definition: Value.h:143
llvm::MachO::RecordLoc RecordLoc
Definition: MachO.h:40
static bool IsAttributeLateParsedExperimentalExt(const IdentifierInfo &II)
returns true iff attribute is annotated with LateAttrParseExperimentalExt in Attr....
Definition: ParseDecl.cpp:98
static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc, SourceLocation EndLoc)
Check if the a start and end source location expand to the same macro.
Definition: ParseDecl.cpp:117
static bool IsAttributeLateParsedStandard(const IdentifierInfo &II)
returns true iff attribute is annotated with LateAttrParseStandard in Attr.td.
Definition: ParseDecl.cpp:108
static bool attributeHasIdentifierArg(const IdentifierInfo &II)
Determine whether the given attribute has an identifier argument.
Definition: ParseDecl.cpp:317
static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II)
Determine whether the given attribute treats kw_this as an identifier.
Definition: ParseDecl.cpp:345
static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II)
Determine whether the given attribute requires parsing its arguments in an unevaluated context or not...
Definition: ParseDecl.cpp:373
static bool isValidAfterIdentifierInDeclarator(const Token &T)
isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the specified token is valid after t...
Definition: ParseDecl.cpp:2938
static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II)
Determine whether the given attribute has a variadic identifier argument.
Definition: ParseDecl.cpp:336
static bool attributeAcceptsExprPack(const IdentifierInfo &II)
Determine if an attribute accepts parameter packs.
Definition: ParseDecl.cpp:354
static bool isPipeDeclarator(const Declarator &D)
Definition: ParseDecl.cpp:6467
static SourceLocation getMissingDeclaratorIdLoc(Declarator &D, SourceLocation Loc)
Definition: ParseDecl.cpp:6675
static void DiagnoseCountAttributedTypeInUnnamedAnon(ParsingDeclSpec &DS, Parser &P)
Definition: ParseDecl.cpp:4790
static bool VersionNumberSeparator(const char Separator)
Definition: ParseDecl.cpp:1104
static bool attributeIsTypeArgAttr(const IdentifierInfo &II)
Determine whether the given attribute parses a type argument.
Definition: ParseDecl.cpp:363
static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang, DeclaratorContext TheContext)
Definition: ParseDecl.cpp:6438
static ParsedAttributeArgumentsProperties attributeStringLiteralListArg(const llvm::Triple &T, const IdentifierInfo &II)
Determine whether the given attribute has an identifier argument.
Definition: ParseDecl.cpp:327
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static constexpr bool isOneOf()
This file declares semantic analysis for CUDA constructs.
This file declares facilities that support code completion.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the clang::TokenKind enum and support functions.
@ Uninitialized
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2341
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Combines information about the source-code form of an attribute, including its syntax and spelling.
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
SourceLocation getOpenLocation() const
SourceLocation getCloseLocation() const
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
SourceLocation getEndLoc() const
Definition: DeclSpec.h:85
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
void setTemplateParamLists(ArrayRef< TemplateParameterList * > L)
Definition: DeclSpec.h:87
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
Represents a character-granular source range.
SourceLocation getBegin() const
Callback handler that receives notifications when performing code completion within the preprocessor.
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed.
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3247
bool isRecord() const
Definition: DeclBase.h:2146
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:645
bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, ExplicitSpecifier ExplicitSpec, SourceLocation CloseParenLoc)
Definition: DeclSpec.cpp:1069
bool isTypeSpecPipe() const
Definition: DeclSpec.h:540
void ClearTypeSpecType()
Definition: DeclSpec.h:520
static const TSCS TSCS___thread
Definition: DeclSpec.h:266
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:309
void setTypeArgumentRange(SourceRange range)
Definition: DeclSpec.h:590
bool SetTypePipe(bool isPipe, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:908
SourceLocation getPipeLoc() const
Definition: DeclSpec.h:619
static const TST TST_typename
Definition: DeclSpec.h:306
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:573
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:688
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:641
static const TST TST_char8
Definition: DeclSpec.h:282
static const TST TST_BFloat16
Definition: DeclSpec.h:289
void ClearStorageClassSpecs()
Definition: DeclSpec.h:512
bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1128
static const TSCS TSCS__Thread_local
Definition: DeclSpec.h:268
bool SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec, but return true and ignore the request if ...
Definition: DeclSpec.cpp:717
bool isNoreturnSpecified() const
Definition: DeclSpec.h:658
TST getTypeSpecType() const
Definition: DeclSpec.h:534
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SCS getStorageClassSpec() const
Definition: DeclSpec.h:498
bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1116
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:856
bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:880
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:571
bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:703
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:706
bool SetBitIntType(SourceLocation KWLoc, Expr *BitWidth, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:967
static const TST TST_auto_type
Definition: DeclSpec.h:319
static const TST TST_interface
Definition: DeclSpec.h:304
static const TST TST_double
Definition: DeclSpec.h:291
static const TST TST_typeofExpr
Definition: DeclSpec.h:308
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:613
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:705
bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:925
bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1103
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:659
static const TST TST_union
Definition: DeclSpec.h:302
static const TST TST_char
Definition: DeclSpec.h:280
static const TST TST_bool
Definition: DeclSpec.h:297
static const TST TST_char16
Definition: DeclSpec.h:283
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:651
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:824
static const TST TST_int
Definition: DeclSpec.h:285
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:827
bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:734
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:785
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:499
bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1088
bool hasAttributes() const
Definition: DeclSpec.h:868
static const TST TST_accum
Definition: DeclSpec.h:293
static const TST TST_half
Definition: DeclSpec.h:288
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:870
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:614
static const TST TST_ibm128
Definition: DeclSpec.h:296
void addAttributes(const ParsedAttributesView &AL)
Concatenates two attribute lists.
Definition: DeclSpec.h:864
static const TST TST_enum
Definition: DeclSpec.h:301
bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:942
static const TST TST_float128
Definition: DeclSpec.h:295
void Finish(Sema &S, const PrintingPolicy &Policy)
Finish - This does final analysis of the declspec, issuing diagnostics for things like "_Imaginary" (...
Definition: DeclSpec.cpp:1150
bool isInlineSpecified() const
Definition: DeclSpec.h:634
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:615
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:310
static const TST TST_class
Definition: DeclSpec.h:305
bool hasTagDefinition() const
Definition: DeclSpec.cpp:459
static const TST TST_decimal64
Definition: DeclSpec.h:299
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition: DeclSpec.cpp:468
void ClearFunctionSpecs()
Definition: DeclSpec.h:661
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1013
static const TST TST_wchar
Definition: DeclSpec.h:281
static const TST TST_void
Definition: DeclSpec.h:279
bool isTypeAltiVecVector() const
Definition: DeclSpec.h:535
void ClearConstexprSpec()
Definition: DeclSpec.h:838
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:558
static const TST TST_float
Definition: DeclSpec.h:290
static const TST TST_atomic
Definition: DeclSpec.h:321
static const TST TST_fract
Definition: DeclSpec.h:294
bool SetTypeSpecError()
Definition: DeclSpec.cpp:959
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:508
Decl * getRepAsDecl() const
Definition: DeclSpec.h:548
static const TST TST_float16
Definition: DeclSpec.h:292
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:617
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:646
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:833
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:568
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
Definition: DeclSpec.h:701
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:579
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:267
bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1054
static const TST TST_decimal32
Definition: DeclSpec.h:298
bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:893
TypeSpecifierWidth getTypeSpecWidth() const
Definition: DeclSpec.h:527
static const TST TST_char32
Definition: DeclSpec.h:284
bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1028
static const TST TST_decimal128
Definition: DeclSpec.h:300
bool isTypeSpecOwned() const
Definition: DeclSpec.h:538
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:637
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:618
static const TST TST_int128
Definition: DeclSpec.h:286
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:616
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:818
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:648
bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:1042
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:834
void takeAttributesFrom(ParsedAttributes &attrs)
Definition: DeclSpec.h:873
static const TST TST_typeofType
Definition: DeclSpec.h:307
bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:744
static const TST TST_auto
Definition: DeclSpec.h:318
@ PQ_FunctionSpecifier
Definition: DeclSpec.h:346
@ PQ_StorageClassSpecifier
Definition: DeclSpec.h:343
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:829
static const TST TST_struct
Definition: DeclSpec.h:303
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2456
bool isPastIdentifier() const
isPastIdentifier - Return true if we have parsed beyond the point where the name would appear.
Definition: DeclSpec.h:2314
void SetRangeBegin(SourceLocation Loc)
SetRangeBegin - Set the start of the source range to Loc, unless it's invalid.
Definition: DeclSpec.h:2089
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2398
void setCommaLoc(SourceLocation CL)
Definition: DeclSpec.h:2723
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2047
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2336
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2339
bool mayOmitIdentifier() const
mayOmitIdentifier - Return true if the identifier is either optional or not allowed.
Definition: DeclSpec.h:2133
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:2084
bool mayBeFollowedByCXXDirectInit() const
mayBeFollowedByCXXDirectInit - Return true if the declarator can be followed by a C++ direct initiali...
Definition: DeclSpec.h:2256
bool hasGroupingParens() const
Definition: DeclSpec.h:2719
void setDecompositionBindings(SourceLocation LSquareLoc, MutableArrayRef< DecompositionDeclarator::Binding > Bindings, SourceLocation RSquareLoc)
Set the decomposition bindings for this declarator.
Definition: DeclSpec.cpp:294
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2713
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2394
bool mayHaveIdentifier() const
mayHaveIdentifier - Return true if the identifier is either optional or required.
Definition: DeclSpec.h:2173
void setGroupingParens(bool flag)
Definition: DeclSpec.h:2718
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:2726
DeclaratorContext getContext() const
Definition: DeclSpec.h:2072
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2083
void setTrailingRequiresClause(Expr *TRC)
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2626
void setHasInitializer(bool Val=true)
Definition: DeclSpec.h:2745
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2066
void setTemplateParameterLists(ArrayRef< TemplateParameterList * > TPLs)
Sets the template parameter lists that preceded the declarator.
Definition: DeclSpec.h:2644
bool isFirstDeclarator() const
Definition: DeclSpec.h:2721
bool hasTrailingRequiresClause() const
Determine whether a trailing requires clause was written in this declarator.
Definition: DeclSpec.h:2639
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2062
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition: DeclSpec.h:2320
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition: DeclSpec.h:2649
bool isFunctionDeclaratorAFunctionDeclaration() const
Return true if a function declarator at this position would be a function declaration.
Definition: DeclSpec.h:2595
bool hasEllipsis() const
Definition: DeclSpec.h:2725
void clear()
Reset the contents of this Declarator.
Definition: DeclSpec.h:2110
void setAsmLabel(Expr *E)
Definition: DeclSpec.h:2701
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2353
void ExtendWithDeclSpec(const DeclSpec &DS)
ExtendWithDeclSpec - Extend the declarator source range to include the given declspec,...
Definition: DeclSpec.h:2101
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
Definition: DeclSpec.h:2094
void setExtension(bool Val=true)
Definition: DeclSpec.h:2704
bool isInvalidType() const
Definition: DeclSpec.h:2714
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2082
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2487
void setEllipsisLoc(SourceLocation EL)
Definition: DeclSpec.h:2727
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2330
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3867
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
This represents one expression.
Definition: Expr.h:110
ExtensionRAIIObject - This saves the state of extension warnings when constructed and disables them.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location.
Definition: Diagnostic.h:110
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
One of these records is kept for each identifier that is lexed.
bool isCPlusPlusKeyword(const LangOptions &LangOpts) const
Return true if this token is a C++ keyword in the specified language.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
bool isKeyword(const LangOptions &LangOpts) const
Return true if this token is a keyword in the specified language.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
StringRef getName() const
Return the actual identifier string.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:658
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
Definition: LangOptions.cpp:79
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition: Lexer.h:78
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
static bool isAtStartOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroBegin=nullptr)
Returns true if the given MacroID location points at the first token of the macro expansion.
Definition: Lexer.cpp:872
static bool isAtEndOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroEnd=nullptr)
Returns true if the given MacroID location points at the last token of the macro expansion.
Definition: Lexer.cpp:894
static bool getRawToken(SourceLocation Loc, Token &Result, const SourceManager &SM, const LangOptions &LangOpts, bool IgnoreWhiteSpace=false)
Relex the token at the specified location.
Definition: Lexer.cpp:510
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Finds the token that comes right after the given location.
Definition: Lexer.cpp:1325
Represents the results of name lookup.
Definition: Lookup.h:46
This represents a decl that may have a name.
Definition: Decl.h:249
PtrTy get() const
Definition: Ownership.h:80
bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const
RAII object that makes sure paren/bracket/brace count is correct after declaration/statement parsing,...
Represents a parameter to a function.
Definition: Decl.h:1761
static constexpr unsigned getMaxFunctionScopeDepth()
Definition: Decl.h:1816
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
unsigned getMaxArgs() const
Definition: ParsedAttr.cpp:150
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:838
void addAtEnd(ParsedAttr *newAttr)
Definition: ParsedAttr.h:848
void addAll(iterator B, iterator E)
Definition: ParsedAttr.h:880
void remove(ParsedAttr *ToBeRemoved)
Definition: ParsedAttr.h:853
SizeType size() const
Definition: ParsedAttr.h:844
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:958
ParsedAttr * addNew(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, ArgsUnion *args, unsigned numArgs, ParsedAttr::Form form, SourceLocation ellipsisLoc=SourceLocation())
Add attribute with expression arguments.
Definition: ParsedAttr.h:991
void takeOneFrom(ParsedAttributes &Other, ParsedAttr *PA)
Definition: ParsedAttr.h:975
ParsedAttr * addNewPropertyAttr(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, IdentifierInfo *getterId, IdentifierInfo *setterId, ParsedAttr::Form formUsed)
Add microsoft __delspec(property) attribute.
Definition: ParsedAttr.h:1058
ParsedAttr * addNewTypeTagForDatatype(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, IdentifierLoc *argumentKind, ParsedType matchingCType, bool layoutCompatible, bool mustBeNull, ParsedAttr::Form form)
Add type_tag_for_datatype attribute.
Definition: ParsedAttr.h:1032
ParsedAttr * addNewTypeAttr(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, ParsedType typeArg, ParsedAttr::Form formUsed, SourceLocation ellipsisLoc=SourceLocation())
Add an attribute with a single type argument.
Definition: ParsedAttr.h:1045
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:58
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeName, AccessSpecifier AS=AS_none, Decl **OwnedType=nullptr, ParsedAttributes *Attrs=nullptr)
ParseTypeName type-name: [C99 6.7.6] specifier-qualifier-list abstract-declarator[opt].
Definition: ParseDecl.cpp:50
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:81
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:545
DeclGroupPtrTy ParseOpenACCDirectiveDecl()
Placeholder for now, should just ignore the directives after emitting a diagnostic.
Sema & getActions() const
Definition: Parser.h:495
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:874
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
Definition: ParseExpr.cpp:380
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition: Parser.h:573
ExprResult ParseConstantExpression()
Definition: ParseExpr.cpp:233
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:553
Scope * getCurScope() const
Definition: Parser.h:499
SourceLocation getEndOfPreviousToken()
Definition: Parser.h:591
ExprResult ParseArrayBoundExpression()
Definition: ParseExpr.cpp:243
const TargetInfo & getTargetInfo() const
Definition: Parser.h:493
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
Definition: Parser.h:1291
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
Definition: ParseDecl.cpp:2160
friend class ObjCDeclContextSwitch
Definition: Parser.h:65
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn't include (top-level) commas.
Definition: ParseExpr.cpp:169
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:223
const LangOptions & getLangOpts() const
Definition: Parser.h:492
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:132
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1272
@ StopAtCodeCompletion
Stop at code completion.
Definition: Parser.h:1273
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1270
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:2000
ExprResult ParseUnevaluatedStringLiteralExpression()
ObjCContainerDecl * getObjCDeclContext() const
Definition: Parser.h:504
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:869
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition: Parser.h:513
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition: Parser.cpp:2234
RAII object used to inform the actions that we're currently parsing a declaration.
A class for parsing a DeclSpec.
A class for parsing a declarator.
A class for parsing a field declarator.
void enterVariableInit(SourceLocation Tok, Decl *D)
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
const LangOptions & getLangOpts() const
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:940
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
The collection of all-type qualifiers we support.
Definition: Type.h:318
void addAddressSpace(LangAS space)
Definition: Type.h:583
void addConst()
Definition: Type.h:446
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition: Type.h:427
Represents a struct/union/class.
Definition: Decl.h:4168
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition: Scope.h:411
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:262
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
Definition: Scope.h:85
@ BlockScope
This is a scope that corresponds to a block/closure object.
Definition: Scope.h:75
@ FriendScope
This is a scope of friend declaration.
Definition: Scope.h:164
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:66
@ AtCatchScope
This is a scope that corresponds to the Objective-C @catch statement.
Definition: Scope.h:95
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
@ CompoundStmtScope
This is a compound statement scope.
Definition: Scope.h:134
@ ClassScope
The scope of a struct/union/class definition.
Definition: Scope.h:69
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
Definition: Scope.h:91
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition: Scope.h:51
@ EnumScope
This scope corresponds to an enum.
Definition: Scope.h:122
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
@ CTCK_InitGlobalVar
Unknown context.
Definition: SemaCUDA.h:121
void CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax, AttributeCompletion Completion=AttributeCompletion::Attribute, const IdentifierInfo *Scope=nullptr)
ParserCompletionContext
Describes the context in which code completion occurs.
@ PCC_LocalDeclarationSpecifiers
Code completion occurs within a sequence of declaration specifiers within a function,...
@ PCC_MemberTemplate
Code completion occurs following one or more template headers within a class.
@ PCC_Class
Code completion occurs within a class, struct, or union.
@ PCC_ObjCImplementation
Code completion occurs within an Objective-C implementation or category implementation.
@ PCC_Namespace
Code completion occurs at top-level or namespace context.
@ PCC_Template
Code completion occurs following one or more template headers.
void CodeCompleteTypeQualifiers(DeclSpec &DS)
void CodeCompleteAfterFunctionEquals(Declarator &D)
QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc, ArrayRef< Expr * > Args, SourceLocation OpenParLoc, bool Braced)
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
void CodeCompleteInitializer(Scope *S, Decl *D)
void CodeCompleteBracketDeclarator(Scope *S)
void CodeCompleteTag(Scope *S, unsigned TagSpec)
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers)
ParsedType ActOnObjCInstanceType(SourceLocation Loc)
The parser has parsed the context-sensitive type 'instancetype' in an Objective-C message declaration...
Definition: SemaObjC.cpp:741
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, const IdentifierInfo *ClassName, SmallVectorImpl< Decl * > &Decls)
Called whenever @defs(ClassName) is encountered in the source.
void startOpenMPCXXRangeFor()
If the current region is a range loop-based region, mark the start of the loop construct.
NameClassificationKind getKind() const
Definition: Sema.h:2780
bool containsUnexpandedParameterPacks(Declarator &D)
Determine whether the given declarator contains any unexpanded parameter packs.
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We've seen a default argument for a function parameter,...
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7289
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5365
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E)
ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression found in an explicit(bool)...
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, Expr *DefaultArg)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
SemaOpenMP & OpenMP()
Definition: Sema.h:1013
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18294
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:15107
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
SemaCUDA & CUDA()
Definition: Sema.h:993
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition: SemaDecl.cpp:647
void ActOnFinishFunctionDeclarationDeclarator(Declarator &D)
Called after parsing a function declarator belonging to a function declaration.
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
ASTContext & Context
Definition: Sema.h:848
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14737
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20352
SemaObjC & ObjC()
Definition: Sema.h:1003
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:67
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
ASTContext & getASTContext() const
Definition: Sema.h:517
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
@ NC_Unknown
This name is not a type or template in this context, but might be something else.
Definition: Sema.h:2672
@ NC_VarTemplate
The name was classified as a variable template name.
Definition: Sema.h:2699
@ NC_NonType
The name was classified as a specific non-type, non-template declaration.
Definition: Sema.h:2682
@ NC_TypeTemplate
The name was classified as a template whose specializations are types.
Definition: Sema.h:2697
@ NC_Error
Classification failed; an error has been produced.
Definition: Sema.h:2674
@ NC_FunctionTemplate
The name was classified as a function template name.
Definition: Sema.h:2701
@ NC_DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition: Sema.h:2690
@ NC_UndeclaredNonType
The name was classified as an ADL-only function name.
Definition: Sema.h:2686
@ NC_UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition: Sema.h:2703
@ NC_Keyword
The name has been typo-corrected to a keyword.
Definition: Sema.h:2676
@ NC_Type
The name was classified as a type.
Definition: Sema.h:2678
@ NC_OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition: Sema.h:2695
@ NC_Concept
The name was classified as a concept name.
Definition: Sema.h:2705
void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth)
Called before parsing a function declarator belonging to a function declaration.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7999
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:765
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19807
const LangOptions & getLangOpts() const
Definition: Sema.h:510
SemaCodeCompletion & CodeCompletion()
Definition: Sema.h:988
@ ReuseLambdaContextDecl
Definition: Sema.h:5194
bool isUnexpandedParameterPackPermitted()
Determine whether an unexpanded parameter pack might be permitted in this location.
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4803
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:880
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D)
Determine if we're in a case where we need to (incorrectly) eagerly parse an exception specification ...
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19833
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14969
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
Definition: Sema.cpp:2730
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18243
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS)
Given an annotation pointer for a nested-name-specifier, restore the nested-name-specifier structure.
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:20088
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18229
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13959
TypeResult ActOnTypeName(Declarator &D)
Definition: SemaType.cpp:6369
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
Definition: SemaDecl.cpp:20343
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14892
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition: SemaDecl.cpp:593
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:291
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:17229
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
Definition: SemaDecl.cpp:4849
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19080
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6364
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:511
@ TUK_Definition
Definition: Sema.h:3168
@ TUK_Declaration
Definition: Sema.h:3167
@ TUK_Friend
Definition: Sema.h:3169
@ TUK_Reference
Definition: Sema.h:3166
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:14001
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13438
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:520
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
Definition: SemaDecl.cpp:18462
void ActOnCXXForRangeDecl(Decl *D)
Definition: SemaDecl.cpp:14286
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6132
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3764
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:701
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:17808
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined.
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
UIntTy getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
A RAII object used to temporarily suppress access-like checking.
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3584
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4720
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:187
SourceLocation getEndLoc() const
Definition: Token.h:159
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
const char * getName() const
Definition: Token.h:174
unsigned getLength() const
Definition: Token.h:135
void setKind(tok::TokenKind K)
Definition: Token.h:95
SourceLocation getAnnotationEndLoc() const
Definition: Token.h:146
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
void * getAnnotationValue() const
Definition: Token.h:234
tok::TokenKind getKind() const
Definition: Token.h:94
bool isRegularKeywordAttribute() const
Return true if the token is a keyword that is parsed in the same position as a standard attribute,...
Definition: Token.h:126
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:276
void setEofData(const void *D)
Definition: Token.h:204
SourceRange getAnnotationRange() const
SourceRange of the group of tokens that this annotation token represents.
Definition: Token.h:166
void setLocation(SourceLocation L)
Definition: Token.h:140
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
const void * getEofData() const
Definition: Token.h:200
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition: Lexer.cpp:61
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:196
A declaration that models statements at global scope.
Definition: Decl.h:4457
void setSemiMissing(bool Missing=true)
Definition: Decl.h:4478
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
The base class of the type hierarchy.
Definition: Type.h:1813
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition: DeclSpec.h:1086
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1234
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1083
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1107
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Declaration of a variable template.
static const char * getSpecifierName(Specifier VS)
Definition: DeclSpec.cpp:1545
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
bool isPragmaAnnotation(TokenKind K)
Return true if this is an annotation token representing a pragma.
Definition: TokenKinds.cpp:68
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_auto
Definition: Specifiers.h:92
@ TST_bool
Definition: Specifiers.h:75
@ TST_unknown_anytype
Definition: Specifiers.h:95
@ TST_decltype_auto
Definition: Specifiers.h:93
bool doesKeywordAttributeTakeArgs(tok::TokenKind Kind)
ImplicitTypenameContext
Definition: DeclSpec.h:1883
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus26
Definition: LangStandard.h:61
@ CPlusPlus17
Definition: LangStandard.h:58
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an ParsedAttr as an argument.
Definition: ParsedAttr.h:113
@ IK_TemplateId
A template-id, e.g., f<int>.
void takeAndConcatenateAttrs(ParsedAttributes &First, ParsedAttributes &Second, ParsedAttributes &Result)
Consumes the attributes from First and Second and concatenates them into Result.
Definition: ParsedAttr.cpp:314
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
DeclaratorContext
Definition: DeclSpec.h:1850
@ Result
The result type of a method or function.
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition: CharInfo.h:115
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:31
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
@ TNK_Dependent_template_name
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
Definition: TemplateKinds.h:50
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
const FunctionProtoType * T
@ Parens
New-expression has a C++98 paren-delimited initializer.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_None
no exception specification
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_none
Definition: Specifiers.h:124
#define false
Definition: stdbool.h:26
Represents information about a change in availability for an entity, which is part of the encoding of...
Definition: ParsedAttr.h:48
VersionTuple Version
The version number at which the change occurred.
Definition: ParsedAttr.h:53
SourceLocation KeywordLoc
The location of the keyword indicating the kind of change.
Definition: ParsedAttr.h:50
SourceRange VersionRange
The source range covering the version number.
Definition: ParsedAttr.h:56
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1425
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1400
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition: DeclSpec.h:1330
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1248
enum clang::DeclaratorChunk::@221 Kind
static DeclaratorChunk getBlockPointer(unsigned TypeQuals, SourceLocation Loc)
Return a DeclaratorChunk for a block.
Definition: DeclSpec.h:1738
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:161
static DeclaratorChunk getPipe(unsigned TypeQuals, SourceLocation Loc)
Return a DeclaratorChunk for a block.
Definition: DeclSpec.h:1748
static DeclaratorChunk getArray(unsigned TypeQuals, bool isStatic, bool isStar, Expr *NumElts, SourceLocation LBLoc, SourceLocation RBLoc)
Return a DeclaratorChunk for an array.
Definition: DeclSpec.h:1695
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1256
static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS, unsigned TypeQuals, SourceLocation StarLoc, SourceLocation EndLoc)
Definition: DeclSpec.h:1757
static DeclaratorChunk getParen(SourceLocation LParenLoc, SourceLocation RParenLoc)
Return a DeclaratorChunk for a paren.
Definition: DeclSpec.h:1773
static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc, SourceLocation ConstQualLoc, SourceLocation VolatileQualLoc, SourceLocation RestrictQualLoc, SourceLocation AtomicQualLoc, SourceLocation UnalignedQualLoc)
Return a DeclaratorChunk for a pointer.
Definition: DeclSpec.h:1664
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1684
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:103
SourceLocation Loc
Definition: ParsedAttr.h:104
IdentifierInfo * Ident
Definition: ParsedAttr.h:105
static IdentifierLoc * create(ASTContext &Ctx, SourceLocation Loc, IdentifierInfo *Ident)
Definition: ParsedAttr.cpp:28
bool isStringLiteralArg(unsigned I) const
Definition: ParsedAttr.h:941
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:5044
bool CheckSameAsPrevious
Definition: Sema.h:353
NamedDecl * New
Definition: Sema.h:355
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
TemplateNameKind Kind
The kind of template that Template refers to.