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