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