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
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/DeclTemplate.h"
15#include "clang/AST/PrettyDeclStackTrace.h"
16#include "clang/Basic/AddressSpaces.h"
17#include "clang/Basic/AttributeCommonInfo.h"
18#include "clang/Basic/Attributes.h"
19#include "clang/Basic/CharInfo.h"
20#include "clang/Basic/DiagnosticParse.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TokenKinds.h"
23#include "clang/Parse/Parser.h"
24#include "clang/Parse/RAIIObjectsForParser.h"
25#include "clang/Sema/EnterExpressionEvaluationContext.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedAttr.h"
28#include "clang/Sema/ParsedTemplate.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/SemaCUDA.h"
31#include "clang/Sema/SemaCodeCompletion.h"
32#include "clang/Sema/SemaObjC.h"
33#include "clang/Sema/SemaOpenMP.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
44TypeResult Parser::ParseTypeName(SourceRange *Range, DeclaratorContext Context,
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(AL: *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) {
61 llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
62 for (ParsedAttr &AL : DS.getAttributes()) {
63 if (AL.isDeclspecAttribute())
64 ToBeMoved.push_back(Elt: &AL);
65 }
66
67 for (ParsedAttr *AL : ToBeMoved)
68 Attrs->takeOneFrom(Other&: DS.getAttributes(), PA: AL);
69 }
70
71 // Parse the abstract-declarator, if present.
72 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
73 ParseDeclarator(D&: DeclaratorInfo);
74 if (Range)
75 *Range = DeclaratorInfo.getSourceRange();
76
77 if (DeclaratorInfo.isInvalidType())
78 return true;
79
80 return Actions.ActOnTypeName(D&: 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(Prefix: "__") && Name.ends_with(Suffix: "__"))
86 return Name.drop_front(N: 2).drop_back(N: 2);
87 return Name;
88}
89
90/// returns true iff attribute is annotated with `LateAttrParseExperimentalExt`
91/// in `Attr.td`.
92static bool IsAttributeLateParsedExperimentalExt(const IdentifierInfo &II) {
93#define CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST
94 return llvm::StringSwitch<bool>(normalizeAttrName(Name: II.getName()))
95#include "clang/Parse/AttrParserStringSwitches.inc"
96 .Default(Value: 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`.
102static bool IsAttributeLateParsedStandard(const IdentifierInfo &II) {
103#define CLANG_ATTR_LATE_PARSED_LIST
104 return llvm::StringSwitch<bool>(normalizeAttrName(Name: II.getName()))
105#include "clang/Parse/AttrParserStringSwitches.inc"
106 .Default(Value: 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.
112static bool IsAttributeArgsParsedInFunctionScope(const IdentifierInfo &II) {
113#define CLANG_ATTR_PARSE_ARGS_IN_FUNCTION_SCOPE_LIST
114 return llvm::StringSwitch<bool>(normalizeAttrName(Name: II.getName()))
115#include "clang/Parse/AttrParserStringSwitches.inc"
116 .Default(Value: 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.
121static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
122 SourceLocation EndLoc) {
123 if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
124 return false;
125
126 SourceManager &SM = PP.getSourceManager();
127 if (SM.getFileID(SpellingLoc: StartLoc) != SM.getFileID(SpellingLoc: EndLoc))
128 return false;
129
130 bool AttrStartIsInMacro =
131 Lexer::isAtStartOfMacroExpansion(loc: StartLoc, SM, LangOpts: PP.getLangOpts());
132 bool AttrEndIsInMacro =
133 Lexer::isAtEndOfMacroExpansion(loc: EndLoc, SM, LangOpts: PP.getLangOpts());
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(K: tok::l_paren)) {
164 Attrs.addNew(attrName: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), args: nullptr, numArgs: 0,
165 form: 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 &&
177 IsAttributeLateParsedExperimentalExt(II: *AttrName);
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(II: *AttrName) ||
184 IsAttributeLateParsedStandard(II: *AttrName);
185 }
186
187 // Handle "parameterized" attributes
188 if (!LateParse) {
189 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc: &EndLoc, ScopeName: nullptr,
190 ScopeLoc: SourceLocation(), Form: ParsedAttr::Form::GNU(), D);
191 return false;
192 }
193
194 // Handle attributes with arguments that require late parsing.
195 LateParsedAttribute *LA =
196 new LateParsedAttribute(this, *AttrName, AttrNameLoc);
197 LateAttrs->push_back(Elt: 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(Elt: 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(Elt: Tok);
207 ConsumeParen();
208 // Consume everything up to and including the matching right parens.
209 ConsumeAndStoreUntil(T1: tok::r_paren, Toks&: LA->Toks, /*StopAtSemi=*/true);
210
211 Token Eof;
212 Eof.startToken();
213 Eof.setLocation(Tok.getLocation());
214 LA->Toks.push_back(Elt: 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(K: tok::kw___attribute)) {
227 SourceLocation AttrTokLoc = ConsumeToken();
228 unsigned OldNumAttrs = Attrs.size();
229 unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
230
231 if (ExpectAndConsume(ExpectedTok: tok::l_paren, Diag: diag::err_expected_lparen_after,
232 DiagMsg: "attribute")) {
233 SkipUntil(T: tok::r_paren, Flags: StopAtSemi); // skip until ) or ;
234 return;
235 }
236 if (ExpectAndConsume(ExpectedTok: tok::l_paren, Diag: diag::err_expected_lparen_after, DiagMsg: "(")) {
237 SkipUntil(T: tok::r_paren, Flags: 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(Expected: tok::comma))
244 ;
245
246 // Expect an identifier or declaration specifier (const, int, etc.)
247 if (Tok.isAnnotation())
248 break;
249 if (Tok.is(K: tok::code_completion)) {
250 cutOffParsing();
251 Actions.CodeCompletion().CodeCompleteAttribute(
252 Syntax: AttributeCommonInfo::Syntax::AS_GNU);
253 break;
254 }
255
256 if (ParseSingleGNUAttribute(Attrs, EndLoc, LateAttrs, D))
257 break;
258 } while (Tok.is(K: tok::comma));
259
260 if (ExpectAndConsume(ExpectedTok: tok::r_paren))
261 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
262 SourceLocation Loc = Tok.getLocation();
263 if (ExpectAndConsume(ExpectedTok: tok::r_paren))
264 SkipUntil(T: tok::r_paren, Flags: 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(Loc: SM.getSpellingLoc(Loc: AttrTokLoc)) &&
271 FindLocsWithCommonFileID(PP, StartLoc: AttrTokLoc, EndLoc: Loc)) {
272 CharSourceRange ExpansionRange = SM.getExpansionRange(Loc: AttrTokLoc);
273 StringRef FoundName =
274 Lexer::getSourceText(Range: ExpansionRange, SM, LangOpts: PP.getLangOpts());
275 IdentifierInfo *MacroII = PP.getIdentifierInfo(Name: FoundName);
276
277 for (unsigned i = OldNumAttrs; i < Attrs.size(); ++i)
278 Attrs[i].setMacroIdentifier(MacroName: MacroII, Loc: 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(Name: II.getName()))
297#include "clang/Parse/AttrParserStringSwitches.inc"
298 .Default(Value: false);
299#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
300}
301
302/// Determine whether the given attribute has string arguments.
303static ParsedAttributeArgumentsProperties
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(Name: II.getName()))
309#include "clang/Parse/AttrParserStringSwitches.inc"
310 .Default(Value: 0);
311#undef CLANG_ATTR_STRING_LITERAL_ARG_LIST
312}
313
314/// Determine whether the given attribute has a variadic identifier argument.
315static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II,
316 ParsedAttr::Syntax Syntax,
317 IdentifierInfo *ScopeName) {
318#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
319 return llvm::StringSwitch<bool>(normalizeAttrName(Name: II.getName()))
320#include "clang/Parse/AttrParserStringSwitches.inc"
321 .Default(Value: false);
322#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
323}
324
325/// Determine whether the given attribute treats kw_this as an identifier.
326static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II,
327 ParsedAttr::Syntax Syntax,
328 IdentifierInfo *ScopeName) {
329#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
330 return llvm::StringSwitch<bool>(normalizeAttrName(Name: II.getName()))
331#include "clang/Parse/AttrParserStringSwitches.inc"
332 .Default(Value: false);
333#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
334}
335
336/// Determine if an attribute accepts parameter packs.
337static bool attributeAcceptsExprPack(const IdentifierInfo &II,
338 ParsedAttr::Syntax Syntax,
339 IdentifierInfo *ScopeName) {
340#define CLANG_ATTR_ACCEPTS_EXPR_PACK
341 return llvm::StringSwitch<bool>(normalizeAttrName(Name: II.getName()))
342#include "clang/Parse/AttrParserStringSwitches.inc"
343 .Default(Value: false);
344#undef CLANG_ATTR_ACCEPTS_EXPR_PACK
345}
346
347/// Determine whether the given attribute parses a type argument.
348static bool attributeIsTypeArgAttr(const IdentifierInfo &II,
349 ParsedAttr::Syntax Syntax,
350 IdentifierInfo *ScopeName) {
351#define CLANG_ATTR_TYPE_ARG_LIST
352 return llvm::StringSwitch<bool>(normalizeAttrName(Name: II.getName()))
353#include "clang/Parse/AttrParserStringSwitches.inc"
354 .Default(Value: false);
355#undef CLANG_ATTR_TYPE_ARG_LIST
356}
357
358/// Determine whether the given attribute takes a strict identifier argument.
359static bool attributeHasStrictIdentifierArgs(const IdentifierInfo &II,
360 ParsedAttr::Syntax Syntax,
361 IdentifierInfo *ScopeName) {
362#define CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST
363 return llvm::StringSwitch<bool>(normalizeAttrName(Name: II.getName()))
364#include "clang/Parse/AttrParserStringSwitches.inc"
365 .Default(Value: 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.
371static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II,
372 ParsedAttr::Syntax Syntax,
373 IdentifierInfo *ScopeName) {
374#define CLANG_ATTR_ARG_CONTEXT_LIST
375 return llvm::StringSwitch<bool>(normalizeAttrName(Name: II.getName()))
376#include "clang/Parse/AttrParserStringSwitches.inc"
377 .Default(Value: 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(K: 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: &AttrName, attrRange: SourceRange(AttrNameLoc, Parens.getCloseLocation()),
411 scope: AttributeScopeInfo(ScopeName, ScopeLoc), typeArg: T.get(), formUsed: Form);
412 else
413 Attrs.addNew(attrName: &AttrName, attrRange: SourceRange(AttrNameLoc, Parens.getCloseLocation()),
414 scope: AttributeScopeInfo(ScopeName, ScopeLoc), args: nullptr, numArgs: 0, form: Form);
415}
416
417ExprResult
418Parser::ParseUnevaluatedStringInAttribute(const IdentifierInfo &AttrName) {
419 if (Tok.is(K: 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(Loc: Tok.getLocation(), DiagID: diag::err_expected_string_literal)
428 << /*in attribute...*/ 4 << AttrName.getName();
429 return ExprError();
430 }
431 return ParseUnevaluatedStringLiteralExpression();
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(I: Arg)) {
441 Expr = ParseUnevaluatedStringInAttribute(AttrName);
442 } else if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::l_brace)) {
443 Diag(Tok, DiagID: diag::warn_cxx98_compat_generalized_initializer_lists);
444 Expr = ParseBraceInitializer();
445 } else {
446 Expr = ParseAssignmentExpression();
447 }
448
449 if (Tok.is(K: tok::ellipsis))
450 Expr = Actions.ActOnPackExpansion(Pattern: Expr.get(), EllipsisLoc: ConsumeToken());
451 else if (Tok.is(K: 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(E: Expr.get())) {
468 SawError = true;
469 break;
470 }
471
472 Exprs.push_back(Elt: Expr.get());
473
474 if (Tok.isNot(K: tok::comma))
475 break;
476 // Move to the next argument, remember where the comma was.
477 Token Comma = Tok;
478 ConsumeToken();
479 checkPotentialAngleBracketDelimiter(OpToken: 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 II: *AttrName, Syntax: Form.getSyntax(), ScopeName);
495 bool AttributeIsTypeArgAttr =
496 attributeIsTypeArgAttr(II: *AttrName, Syntax: Form.getSyntax(), ScopeName);
497 bool AttributeHasVariadicIdentifierArg =
498 attributeHasVariadicIdentifierArg(II: *AttrName, Syntax: Form.getSyntax(), ScopeName);
499
500 // Interpret "kw_this" as an identifier if the attributed requests it.
501 if (ChangeKWThisToIdent && Tok.is(K: tok::kw_this))
502 Tok.setKind(tok::identifier);
503
504 ArgsVector ArgExprs;
505 if (Tok.is(K: tok::identifier)) {
506 // If this attribute wants an 'identifier' argument, make it so.
507 bool IsIdentifierArg =
508 AttributeHasVariadicIdentifierArg ||
509 attributeHasIdentifierArg(T: getTargetInfo().getTriple(), II: *AttrName,
510 Syntax: Form.getSyntax(), ScopeName);
511 ParsedAttr::Kind AttrKind =
512 ParsedAttr::getParsedKind(Name: AttrName, Scope: ScopeName, SyntaxUsed: 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(Ks: tok::r_paren, Ks: tok::comma);
520 }
521
522 if (IsIdentifierArg)
523 ArgExprs.push_back(Elt: ParseIdentifierLoc());
524 }
525
526 ParsedType TheParsedType;
527 if (!ArgExprs.empty() ? Tok.is(K: tok::comma) : Tok.isNot(K: 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.
534 TypeResult T = ParseTypeName();
535 if (T.isInvalid()) {
536 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
537 return 0;
538 }
539 if (T.isUsable())
540 TheParsedType = T.get();
541 } else if (AttributeHasVariadicIdentifierArg ||
542 attributeHasStrictIdentifierArgs(II: *AttrName, Syntax: Form.getSyntax(),
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(K: tok::kw_this))
552 Tok.setKind(tok::identifier);
553
554 ExprResult ArgExpr;
555 if (Tok.is(K: tok::identifier)) {
556 ArgExprs.push_back(Elt: ParseIdentifierLoc());
557 } else {
558 bool Uneval = attributeParsedArgsUnevaluated(
559 II: *AttrName, Syntax: Form.getSyntax(), ScopeName);
560 EnterExpressionEvaluationContext Unevaluated(
561 Actions,
562 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
563 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
564 nullptr,
565 Sema::ExpressionEvaluationContextRecord::EK_AttrArgument);
566
567 ExprResult ArgExpr = ParseAssignmentExpression();
568 if (ArgExpr.isInvalid()) {
569 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
570 return 0;
571 }
572 ArgExprs.push_back(Elt: ArgExpr.get());
573 }
574 // Eat the comma, move to the next argument
575 } while (TryConsumeToken(Expected: tok::comma));
576 } else {
577 // General case. Parse all available expressions.
578 bool Uneval = attributeParsedArgsUnevaluated(II: *AttrName, Syntax: Form.getSyntax(),
579 ScopeName);
580 EnterExpressionEvaluationContext Unevaluated(
581 Actions,
582 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
583 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
584 nullptr,
585 Sema::ExpressionEvaluationContextRecord::ExpressionKind::
586 EK_AttrArgument);
587
588 ExprVector ParsedExprs;
589 ParsedAttributeArgumentsProperties ArgProperties =
590 attributeStringLiteralListArg(T: getTargetInfo().getTriple(), II: *AttrName,
591 Syntax: Form.getSyntax(), ScopeName);
592 if (ParseAttributeArgumentList(AttrName: *AttrName, Exprs&: ParsedExprs, ArgsProperties: ArgProperties,
593 Arg: ArgExprs.size())) {
594 SkipUntil(T: tok::r_paren, Flags: 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>(Val: ParsedExprs[I]))
601 continue;
602
603 if (!attributeAcceptsExprPack(II: *AttrName, Syntax: Form.getSyntax(), ScopeName)) {
604 Diag(Loc: Tok.getLocation(),
605 DiagID: diag::err_attribute_argument_parm_pack_not_supported)
606 << AttrName;
607 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
608 return 0;
609 }
610 }
611
612 llvm::append_range(C&: ArgExprs, R&: ParsedExprs);
613 }
614 }
615
616 SourceLocation RParen = Tok.getLocation();
617 if (!ExpectAndConsume(ExpectedTok: tok::r_paren)) {
618 SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
619
620 if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
621 Attrs.addNewTypeAttr(attrName: AttrName, attrRange: SourceRange(AttrNameLoc, RParen),
622 scope: AttributeScopeInfo(ScopeName, ScopeLoc),
623 typeArg: TheParsedType, formUsed: Form);
624 } else {
625 Attrs.addNew(attrName: AttrName, attrRange: SourceRange(AttrLoc, RParen),
626 scope: AttributeScopeInfo(ScopeName, ScopeLoc), args: ArgExprs.data(),
627 numArgs: ArgExprs.size(), form: 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(Name: AttrName, Scope: ScopeName, SyntaxUsed: Form.getSyntax());
646
647 if (AttrKind == ParsedAttr::AT_Availability) {
648 ParseAvailabilityAttribute(Availability&: *AttrName, AvailabilityLoc: AttrNameLoc, attrs&: Attrs, endLoc: EndLoc, ScopeName,
649 ScopeLoc, Form);
650 return;
651 } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
652 ParseExternalSourceSymbolAttribute(ExternalSourceSymbol&: *AttrName, Loc: AttrNameLoc, Attrs, EndLoc,
653 ScopeName, ScopeLoc, Form);
654 return;
655 } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
656 ParseObjCBridgeRelatedAttribute(ObjCBridgeRelated&: *AttrName, ObjCBridgeRelatedLoc: AttrNameLoc, Attrs, EndLoc,
657 ScopeName, ScopeLoc, Form);
658 return;
659 } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
660 ParseSwiftNewTypeAttribute(AttrName&: *AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
661 ScopeLoc, Form);
662 return;
663 } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
664 ParseTypeTagForDatatypeAttribute(AttrName&: *AttrName, AttrNameLoc, Attrs, EndLoc,
665 ScopeName, ScopeLoc, Form);
666 return;
667 } else if (attributeIsTypeArgAttr(II: *AttrName, Syntax: Form.getSyntax(), ScopeName)) {
668 ParseAttributeWithTypeArg(AttrName&: *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&: *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(II: *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) {
693 if (D->getTypeObject(i).Kind == DeclaratorChunk::Function) {
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(
704 args: this, args: Scope::FunctionPrototypeScope |
705 Scope::FunctionDeclarationScope | Scope::DeclScope |
706 (getCurScope()->getFlags() & Scope::ClassScope));
707 for (unsigned i = 0; i < FTI->NumParams; ++i)
708 Actions.ActOnReenterCXXMethodParameter(
709 S: getCurScope(), Param: dyn_cast_or_null<ParmVarDecl>(Val: 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(Name: AttrName, Scope: ScopeName, SyntaxUsed: 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(ExternalSourceSymbol&: *AttrName, Loc: AttrNameLoc, Attrs, EndLoc,
732 ScopeName, ScopeLoc, Form);
733 break;
734 case ParsedAttr::AT_Availability:
735 ParseAvailabilityAttribute(Availability&: *AttrName, AvailabilityLoc: AttrNameLoc, attrs&: Attrs, endLoc: EndLoc, ScopeName,
736 ScopeLoc, Form);
737 break;
738 case ParsedAttr::AT_ObjCBridgeRelated:
739 ParseObjCBridgeRelatedAttribute(ObjCBridgeRelated&: *AttrName, ObjCBridgeRelatedLoc: AttrNameLoc, Attrs, EndLoc,
740 ScopeName, ScopeLoc, Form);
741 break;
742 case ParsedAttr::AT_SwiftNewType:
743 ParseSwiftNewTypeAttribute(AttrName&: *AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
744 ScopeLoc, Form);
745 break;
746 case ParsedAttr::AT_TypeTagForDatatype:
747 ParseTypeTagForDatatypeAttribute(AttrName&: *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.
766 if (!hasAttribute(Syntax: AttributeCommonInfo::Syntax::AS_Declspec, Scope: nullptr, Attr: AttrName,
767 Target: getTargetInfo(), LangOpts: getLangOpts())) {
768 // Eat the left paren, then skip to the ending right paren.
769 ConsumeParen();
770 SkipUntil(T: 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(DiagID: diag::err_expected_lparen_after,
783 Msg: AttrName->getNameStart(), SkipToTok: 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(K: tok::identifier)) {
797 // If the user wrote a completely empty list, use a special diagnostic.
798 if (Tok.is(K: tok::r_paren) && !HasInvalidAccessor &&
799 AccessorNames[AK_Put] == nullptr &&
800 AccessorNames[AK_Get] == nullptr) {
801 Diag(Loc: AttrNameLoc, DiagID: diag::err_ms_property_no_getter_or_putter);
802 break;
803 }
804
805 Diag(Loc: Tok.getLocation(), DiagID: 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(Loc: KindLoc, DiagID: diag::err_ms_property_has_set_accessor)
820 << FixItHint::CreateReplacement(RemoveRange: KindLoc, Code: "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(K: tok::comma) || NextToken().is(K: tok::r_paren)) {
826 Diag(Loc: KindLoc, DiagID: 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(Loc: KindLoc, DiagID: 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(K: tok::equal))
839 break;
840 }
841
842 // Consume the identifier.
843 ConsumeToken();
844
845 // Consume the '='.
846 if (!TryConsumeToken(Expected: tok::equal)) {
847 Diag(Loc: Tok.getLocation(), DiagID: diag::err_ms_property_expected_equal)
848 << KindStr;
849 break;
850 }
851
852 // Expect the method name.
853 if (!Tok.is(K: tok::identifier)) {
854 Diag(Loc: Tok.getLocation(), DiagID: 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(Loc: KindLoc, DiagID: 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(Expected: tok::comma))
871 continue;
872
873 // If we run into the ')', stop without consuming it.
874 if (Tok.is(K: tok::r_paren))
875 break;
876
877 Diag(Loc: Tok.getLocation(), DiagID: 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: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(),
884 getterId: AccessorNames[AK_Get], setterId: AccessorNames[AK_Put],
885 formUsed: ParsedAttr::Form::Declspec());
886 T.skipToEnd();
887 return !HasInvalidAccessor;
888 }
889
890 unsigned NumArgs =
891 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc: nullptr, ScopeName: nullptr,
892 ScopeLoc: SourceLocation(), Form: 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(Loc: OpenParenLoc, DiagID: 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(K: tok::kw___declspec)) {
911 ConsumeToken();
912 BalancedDelimiterTracker T(*this, tok::l_paren);
913 if (T.expectAndConsume(DiagID: diag::err_expected_lparen_after, Msg: "__declspec",
914 SkipToTok: 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(K: tok::r_paren)) {
920 // Attribute not present.
921 if (TryConsumeToken(Expected: tok::comma))
922 continue;
923
924 if (Tok.is(K: tok::code_completion)) {
925 cutOffParsing();
926 Actions.CodeCompletion().CodeCompleteAttribute(
927 Syntax: AttributeCommonInfo::AS_Declspec);
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, DiagID: 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, Buffer&: StrBuffer, Invalid: &Invalid);
947 if (Invalid) {
948 T.skipToEnd();
949 return;
950 }
951 AttrName = PP.getIdentifierInfo(Name: 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(K: 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(Loc: Tok.getLocation(), DiagID: diag::err_expected_lparen_after)
966 << AttrName->getName();
967
968 if (!AttrHandled)
969 Attrs.addNew(attrName: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), args: nullptr, numArgs: 0,
970 form: 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: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), args: nullptr, numArgs: 0,
998 form: 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(Loc: StartLoc, DiagID: diag::err_wasm_funcref_not_wasm);
1013 return;
1014 }
1015
1016 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1017 SourceLocation AttrNameLoc = ConsumeToken();
1018 attrs.addNew(attrName: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), /*Args=*/args: nullptr,
1019 /*numArgs=*/0, form: 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(Loc: StartLoc, DiagID: 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(K: tok::kw___pascal)) {
1061 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1062 SourceLocation AttrNameLoc = ConsumeToken();
1063 attrs.addNew(attrName: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), args: nullptr, numArgs: 0,
1064 form: tok::kw___pascal);
1065 }
1066}
1067
1068void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
1069 // Treat these like attributes
1070 while (Tok.is(K: tok::kw___kernel)) {
1071 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1072 SourceLocation AttrNameLoc = ConsumeToken();
1073 attrs.addNew(attrName: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), args: nullptr, numArgs: 0,
1074 form: tok::kw___kernel);
1075 }
1076}
1077
1078void Parser::ParseCUDAFunctionAttributes(ParsedAttributes &attrs) {
1079 while (Tok.is(K: tok::kw___noinline__)) {
1080 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1081 SourceLocation AttrNameLoc = ConsumeToken();
1082 attrs.addNew(attrName: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), args: nullptr, numArgs: 0,
1083 form: 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: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), args: nullptr, numArgs: 0,
1091 form: Tok.getKind());
1092}
1093
1094bool Parser::isHLSLQualifier(const Token &Tok) const {
1095 return Tok.is(K: tok::kw_groupshared) || Tok.is(K: tok::kw_row_major) ||
1096 Tok.is(K: 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: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), args: nullptr, numArgs: 0, form: 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(Loc: AttrNameLoc, DiagID: diag::ext_nullability)
1119 << AttrName;
1120 attrs.addNew(attrName: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(), args: nullptr, numArgs: 0,
1121 form: 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(K: tok::numeric_constant)) {
1138 Diag(Tok, DiagID: diag::err_expected_version);
1139 SkipUntil(T1: tok::comma, T2: tok::r_paren,
1140 Flags: StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
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(N: 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, Buffer&: ThisTokBegin, Invalid: &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(c: ThisTokBegin[AfterMajor])) {
1162 Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
1163 ++AfterMajor;
1164 }
1165
1166 if (AfterMajor == 0) {
1167 Diag(Tok, DiagID: diag::err_expected_version);
1168 SkipUntil(T1: tok::comma, T2: tok::r_paren,
1169 Flags: StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
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, DiagID: diag::err_zero_version);
1179 return VersionTuple();
1180 }
1181
1182 return VersionTuple(Major);
1183 }
1184
1185 const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
1186 if (!VersionNumberSeparator(Separator: AfterMajorSeparator)
1187 || (AfterMajor + 1 == ActualLength)) {
1188 Diag(Tok, DiagID: diag::err_expected_version);
1189 SkipUntil(T1: tok::comma, T2: tok::r_paren,
1190 Flags: StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1191 return VersionTuple();
1192 }
1193
1194 // Parse the minor version.
1195 unsigned AfterMinor = AfterMajor + 1;
1196 unsigned Minor = 0;
1197 while (AfterMinor < ActualLength && isDigit(c: 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, DiagID: 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(Separator: AfterMinorSeparator)) {
1217 Diag(Tok, DiagID: diag::err_expected_version);
1218 SkipUntil(T1: tok::comma, T2: tok::r_paren,
1219 Flags: StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1220 return VersionTuple();
1221 }
1222
1223 // Warn if separators, be it '.' or '_', do not match.
1224 if (AfterMajorSeparator != AfterMinorSeparator)
1225 Diag(Tok, DiagID: 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(c: ThisTokBegin[AfterSubminor])) {
1231 Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
1232 ++AfterSubminor;
1233 }
1234
1235 if (AfterSubminor != ActualLength) {
1236 Diag(Tok, DiagID: diag::err_expected_version);
1237 SkipUntil(T1: tok::comma, T2: tok::r_paren,
1238 Flags: StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
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, DiagID: diag::err_expected) << tok::l_paren;
1258 return;
1259 }
1260
1261 // Parse the platform name.
1262 if (Tok.isNot(K: tok::identifier)) {
1263 Diag(Tok, DiagID: diag::err_availability_expected_platform);
1264 SkipUntil(T: tok::r_paren, Flags: 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(Other: "xrOS") || Ident->getName().contains(Other: "xros"))
1271 Diag(Loc: Platform->getLoc(), DiagID: 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(Name: "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(Name: "macos_app_extension"));
1280 else
1281 Platform->setIdentifierInfo(PP.getIdentifierInfo(
1282 Name: AvailabilityAttr::canonicalizePlatformName(Platform: Ident->getName())));
1283 }
1284
1285 // Parse the ',' following the platform name.
1286 if (ExpectAndConsume(ExpectedTok: tok::comma)) {
1287 SkipUntil(T: tok::r_paren, Flags: 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(Name: "introduced");
1295 Ident_deprecated = PP.getIdentifierInfo(Name: "deprecated");
1296 Ident_obsoleted = PP.getIdentifierInfo(Name: "obsoleted");
1297 Ident_unavailable = PP.getIdentifierInfo(Name: "unavailable");
1298 Ident_message = PP.getIdentifierInfo(Name: "message");
1299 Ident_strict = PP.getIdentifierInfo(Name: "strict");
1300 Ident_replacement = PP.getIdentifierInfo(Name: "replacement");
1301 Ident_environment = PP.getIdentifierInfo(Name: "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(K: tok::identifier)) {
1309 Diag(Tok, DiagID: diag::err_availability_expected_change);
1310 SkipUntil(T: tok::r_paren, Flags: 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(Loc: KeywordLoc, DiagID: 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(Loc: KeywordLoc, DiagID: 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(Str: "swift")) {
1336 // For swift, we deprecate for all versions.
1337 if (Changes[Deprecated].KeywordLoc.isValid()) {
1338 Diag(Loc: KeywordLoc, DiagID: 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(Loc: KeywordLoc, DiagID: diag::err_availability_redundant)
1352 << Keyword << SourceRange(EnvironmentLoc->getLoc());
1353 }
1354 }
1355
1356 if (Tok.isNot(K: tok::equal)) {
1357 Diag(Tok, DiagID: diag::err_expected_after) << Keyword << tok::equal;
1358 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
1359 return;
1360 }
1361 ConsumeToken();
1362 if (Keyword == Ident_message || Keyword == Ident_replacement) {
1363 if (!isTokenStringLiteral()) {
1364 Diag(Tok, DiagID: diag::err_expected_string_literal)
1365 << /*Source='availability attribute'*/2;
1366 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
1367 return;
1368 }
1369 if (Keyword == Ident_message) {
1370 MessageExpr = ParseUnevaluatedStringLiteralExpression();
1371 break;
1372 } else {
1373 ReplacementExpr = ParseUnevaluatedStringLiteralExpression();
1374 continue;
1375 }
1376 }
1377 if (Keyword == Ident_environment) {
1378 if (Tok.isNot(K: tok::identifier)) {
1379 Diag(Tok, DiagID: diag::err_availability_expected_environment);
1380 SkipUntil(T: tok::r_paren, Flags: 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(K: 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(Range&: VersionRange);
1402
1403 if (Version.empty()) {
1404 SkipUntil(T: tok::r_paren, Flags: 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(Loc: KeywordLoc, DiagID: 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(Loc: KeywordLoc, DiagID: diag::err_availability_unknown_change)
1431 << Keyword << VersionRange;
1432 }
1433
1434 } while (TryConsumeToken(Expected: 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(Loc: UnavailableLoc, DiagID: 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(attrName: &Availability,
1464 attrRange: SourceRange(AvailabilityLoc, T.getCloseLocation()),
1465 scope: AttributeScopeInfo(ScopeName, ScopeLoc), Param: Platform,
1466 introduced: Changes[Introduced], deprecated: Changes[Deprecated], obsoleted: Changes[Obsoleted],
1467 unavailable: UnavailableLoc, MessageExpr: MessageExpr.get(), form: Form, strict: StrictLoc,
1468 ReplacementExpr: 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(Name: "language");
1483 Ident_defined_in = PP.getIdentifierInfo(Name: "defined_in");
1484 Ident_generated_declaration = PP.getIdentifierInfo(Name: "generated_declaration");
1485 Ident_USR = PP.getIdentifierInfo(Name: "USR");
1486 }
1487
1488 ExprResult Language;
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(K: tok::identifier)) {
1499 Diag(Tok, DiagID: diag::err_external_source_symbol_expected_keyword);
1500 SkipUntil(T: tok::r_paren, Flags: 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, DiagID: diag::err_external_source_symbol_duplicate_clause) << Keyword;
1509 SkipUntil(T: tok::r_paren, Flags: 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, DiagID: diag::err_external_source_symbol_expected_keyword);
1519 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
1520 return;
1521 }
1522
1523 ConsumeToken();
1524 if (ExpectAndConsume(ExpectedTok: tok::equal, Diag: diag::err_expected_after,
1525 DiagMsg: Keyword->getName())) {
1526 SkipUntil(T: tok::r_paren, Flags: 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, DiagID: 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(T1: tok::comma, T2: tok::r_paren, Flags: StopAtSemi | StopBeforeMatch);
1547 continue;
1548 }
1549 if (Keyword == Ident_language) {
1550 if (HadLanguage) {
1551 Diag(Loc: KeywordLoc, DiagID: diag::err_external_source_symbol_duplicate_clause)
1552 << Keyword;
1553 ParseUnevaluatedStringLiteralExpression();
1554 continue;
1555 }
1556 Language = ParseUnevaluatedStringLiteralExpression();
1557 } else if (Keyword == Ident_USR) {
1558 if (HadUSR) {
1559 Diag(Loc: KeywordLoc, DiagID: diag::err_external_source_symbol_duplicate_clause)
1560 << Keyword;
1561 ParseUnevaluatedStringLiteralExpression();
1562 continue;
1563 }
1564 USR = ParseUnevaluatedStringLiteralExpression();
1565 } else {
1566 assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1567 if (HadDefinedIn) {
1568 Diag(Loc: KeywordLoc, DiagID: diag::err_external_source_symbol_duplicate_clause)
1569 << Keyword;
1570 ParseUnevaluatedStringLiteralExpression();
1571 continue;
1572 }
1573 DefinedInExpr = ParseUnevaluatedStringLiteralExpression();
1574 }
1575 } while (TryConsumeToken(Expected: 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(attrName: &ExternalSourceSymbol, attrRange: SourceRange(Loc, T.getCloseLocation()),
1586 scope: AttributeScopeInfo(ScopeName, ScopeLoc), args: Args, numArgs: std::size(Args),
1587 form: 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, DiagID: diag::err_expected) << tok::l_paren;
1598 return;
1599 }
1600
1601 // Parse the related class name.
1602 if (Tok.isNot(K: tok::identifier)) {
1603 Diag(Tok, DiagID: diag::err_objcbridge_related_expected_related_class);
1604 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
1605 return;
1606 }
1607 IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1608 if (ExpectAndConsume(ExpectedTok: tok::comma)) {
1609 SkipUntil(T: tok::r_paren, Flags: 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(K: tok::identifier)) {
1618 ClassMethod = ParseIdentifierLoc();
1619 if (!TryConsumeToken(Expected: tok::colon)) {
1620 Diag(Tok, DiagID: diag::err_objcbridge_related_selector_name);
1621 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
1622 return;
1623 }
1624 }
1625 if (!TryConsumeToken(Expected: tok::comma)) {
1626 if (Tok.is(K: tok::colon))
1627 Diag(Tok, DiagID: diag::err_objcbridge_related_selector_name);
1628 else
1629 Diag(Tok, DiagID: diag::err_expected) << tok::comma;
1630 SkipUntil(T: tok::r_paren, Flags: 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(K: tok::identifier))
1638 InstanceMethod = ParseIdentifierLoc();
1639 else if (Tok.isNot(K: tok::r_paren)) {
1640 Diag(Tok, DiagID: diag::err_expected) << tok::r_paren;
1641 SkipUntil(T: tok::r_paren, Flags: 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(attrName: &ObjCBridgeRelated,
1654 attrRange: SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1655 scope: AttributeScopeInfo(ScopeName, ScopeLoc), Param1: RelatedClass,
1656 Param2: ClassMethod, Param3: InstanceMethod, form: 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, DiagID: diag::err_expected) << tok::l_paren;
1668 return;
1669 }
1670
1671 if (Tok.is(K: tok::r_paren)) {
1672 Diag(Loc: Tok.getLocation(), DiagID: diag::err_argument_required_after_attribute);
1673 T.consumeClose();
1674 return;
1675 }
1676 if (Tok.isNot(K: tok::kw_struct) && Tok.isNot(K: tok::kw_enum)) {
1677 Diag(Tok, DiagID: 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: &AttrName, attrRange: SourceRange(AttrNameLoc, T.getCloseLocation()),
1697 scope: AttributeScopeInfo(ScopeName, ScopeLoc), args: Args, numArgs: std::size(Args),
1698 form: 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(K: tok::identifier)) {
1711 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
1712 T.skipToEnd();
1713 return;
1714 }
1715 IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1716
1717 if (ExpectAndConsume(ExpectedTok: tok::comma)) {
1718 T.skipToEnd();
1719 return;
1720 }
1721
1722 SourceRange MatchingCTypeRange;
1723 TypeResult MatchingCType = ParseTypeName(Range: &MatchingCTypeRange);
1724 if (MatchingCType.isInvalid()) {
1725 T.skipToEnd();
1726 return;
1727 }
1728
1729 bool LayoutCompatible = false;
1730 bool MustBeNull = false;
1731 while (TryConsumeToken(Expected: tok::comma)) {
1732 if (Tok.isNot(K: tok::identifier)) {
1733 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
1734 T.skipToEnd();
1735 return;
1736 }
1737 IdentifierInfo *Flag = Tok.getIdentifierInfo();
1738 if (Flag->isStr(Str: "layout_compatible"))
1739 LayoutCompatible = true;
1740 else if (Flag->isStr(Str: "must_be_null"))
1741 MustBeNull = true;
1742 else {
1743 Diag(Tok, DiagID: diag::err_type_safety_unknown_flag) << Flag;
1744 T.skipToEnd();
1745 return;
1746 }
1747 ConsumeToken(); // consume flag
1748 }
1749
1750 if (!T.consumeClose()) {
1751 Attrs.addNewTypeTagForDatatype(
1752 attrName: &AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(ScopeName, ScopeLoc),
1753 argumentKind: ArgumentKind, matchingCType: MatchingCType.get(), layoutCompatible: LayoutCompatible, mustBeNull: MustBeNull, form: 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)) {
1764 case CXX11AttributeKind::NotAttributeSpecifier:
1765 // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1766 return false;
1767
1768 case CXX11AttributeKind::InvalidAttributeSpecifier:
1769 Diag(Loc: Tok.getLocation(), DiagID: diag::err_l_square_l_square_not_attribute);
1770 return false;
1771
1772 case CXX11AttributeKind::AttributeSpecifier:
1773 // Parse and discard the attributes.
1774 SourceLocation BeginLoc = ConsumeBracket();
1775 ConsumeBracket();
1776 SkipUntil(T: tok::r_square);
1777 assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1778 SourceLocation EndLoc = ConsumeBracket();
1779 Diag(Loc: BeginLoc, DiagID: 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&: Attrs);
1796 CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1797 // FIXME: use err_attributes_misplaced
1798 (Keyword ? Diag(Loc, DiagID: diag::err_keyword_not_allowed) << Keyword
1799 : Diag(Loc, DiagID: diag::err_attributes_not_allowed))
1800 << FixItHint::CreateInsertionFromRange(InsertionLoc: CorrectLocation, FromRange: AttrRange)
1801 << FixItHint::CreateRemoval(RemoveRange: 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(Loc: CorrectLocation, DiagID: diag::err_keyword_misplaced) << FirstAttr
1811 : Diag(Loc: CorrectLocation, DiagID: diag::err_attributes_misplaced))
1812 << FixItHint::CreateInsertionFromRange(InsertionLoc: CorrectLocation, FromRange: AttrRange)
1813 << FixItHint::CreateRemoval(RemoveRange: AttrRange);
1814 } else {
1815 const SourceRange &Range = Attrs.Range;
1816 (FirstAttr && FirstAttr->isRegularKeywordAttribute()
1817 ? Diag(Loc: Range.getBegin(), DiagID: diag::err_keyword_not_allowed) << FirstAttr
1818 : Diag(Loc: Range.getBegin(), DiagID: 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(Loc: Attrs.Range.getBegin(), Result&: FirstLSquare, SM, LangOpts);
1836
1837 if (FirstLSquare.is(K: tok::l_square)) {
1838 std::optional<Token> SecondLSquare =
1839 Lexer::findNextToken(Loc: FirstLSquare.getLocation(), SM, LangOpts);
1840
1841 if (SecondLSquare && SecondLSquare->is(K: 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(Loc: Attrs.Range.getBegin(), DiagID: AttrDiagID) << Attrs.Range;
1846 return;
1847 }
1848 }
1849 }
1850
1851 for (const ParsedAttr &AL : Attrs) {
1852 if (AL.isRegularKeywordAttribute()) {
1853 Diag(Loc: AL.getLoc(), DiagID: 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(Loc: AL.getLoc(), DiagID: 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(Loc: PA.getLoc(), DiagID: 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(Elt: &AL);
1891 }
1892
1893 for (ParsedAttr *AL : ToBeMoved) {
1894 DS.getAttributes().remove(ToBeRemoved: AL);
1895 Attrs.addAtEnd(newAttr: 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(Attrs&: DeclAttrs);
1914 ProhibitAttributes(Attrs&: DeclSpecAttrs);
1915 return ParseDeclarationStartingWithTemplate(Context, DeclEnd, AccessAttrs&: 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(K: tok::kw_namespace)) {
1919 ProhibitAttributes(Attrs&: DeclAttrs);
1920 ProhibitAttributes(Attrs&: DeclSpecAttrs);
1921 SourceLocation InlineLoc = ConsumeToken();
1922 return ParseNamespace(Context, DeclEnd, InlineLoc);
1923 }
1924 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1925 RequireSemi: true, FRI: nullptr, DeclSpecStart);
1926
1927 case tok::kw_cbuffer:
1928 case tok::kw_tbuffer:
1929 SingleDecl = ParseHLSLBuffer(DeclEnd, Attrs&: DeclAttrs);
1930 break;
1931 case tok::kw_namespace:
1932 ProhibitAttributes(Attrs&: DeclAttrs);
1933 ProhibitAttributes(Attrs&: DeclSpecAttrs);
1934 return ParseNamespace(Context, DeclEnd);
1935 case tok::kw_using: {
1936 takeAndConcatenateAttrs(First&: DeclAttrs, Second: std::move(DeclSpecAttrs));
1937 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo: ParsedTemplateInfo(),
1938 DeclEnd, Attrs&: DeclAttrs);
1939 }
1940 case tok::kw_static_assert:
1941 case tok::kw__Static_assert:
1942 ProhibitAttributes(Attrs&: DeclAttrs);
1943 ProhibitAttributes(Attrs&: DeclSpecAttrs);
1944 SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1945 break;
1946 default:
1947 return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1948 RequireSemi: true, FRI: 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(Ptr: 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(B: DeclSpecAttrs.begin(), E: DeclSpecAttrs.end());
1963 OriginalDeclSpecAttrs.Range = DeclSpecAttrs.Range;
1964
1965 // Parse the common declaration-specifiers piece.
1966 ParsingDeclSpec DS(*this);
1967 DS.takeAttributesAppendingingFrom(attrs&: DeclSpecAttrs);
1968
1969 ParsedTemplateInfo TemplateInfo;
1970 DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1971 ParseDeclarationSpecifiers(DS, TemplateInfo, AS: AS_none, DSC: 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: 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(K: tok::semi)) {
1982 ProhibitAttributes(Attrs&: DeclAttrs);
1983 DeclEnd = Tok.getLocation();
1984 if (RequireSemi) ConsumeToken();
1985 RecordDecl *AnonRecord = nullptr;
1986 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1987 S: getCurScope(), AS: AS_none, DS, DeclAttrs: ParsedAttributesView::none(), AnonRecord);
1988 Actions.ActOnDefinedDeclarationSpecifier(D: TheDecl);
1989 DS.complete(D: TheDecl);
1990 if (AnonRecord) {
1991 Decl* decls[] = {AnonRecord, TheDecl};
1992 return Actions.BuildDeclaratorGroup(Group: decls);
1993 }
1994 return Actions.ConvertDeclToDeclGroup(Ptr: TheDecl);
1995 }
1996
1997 if (DS.hasTagDefinition())
1998 Actions.ActOnDefinedDeclarationSpecifier(D: DS.getRepAsDecl());
1999
2000 if (DeclSpecStart)
2001 DS.SetRangeStart(*DeclSpecStart);
2002
2003 return ParseDeclGroup(DS, Context, Attrs&: DeclAttrs, TemplateInfo, DeclEnd: &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(K: 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(Tok: NextToken());
2060
2061 default:
2062 return Tok.isRegularKeywordAttribute();
2063 }
2064
2065 default:
2066 return Tok.isRegularKeywordAttribute();
2067 }
2068}
2069
2070void Parser::SkipMalformedDecl() {
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(T: tok::r_brace);
2078 if (Tok.isOneOf(Ks: tok::comma, Ks: tok::l_brace, Ks: tok::kw_try)) {
2079 // This declaration isn't over yet. Keep skipping.
2080 continue;
2081 }
2082 TryConsumeToken(Expected: tok::semi);
2083 return;
2084
2085 case tok::l_square:
2086 ConsumeBracket();
2087 SkipUntil(T: tok::r_square);
2088 continue;
2089
2090 case tok::l_paren:
2091 ConsumeParen();
2092 SkipUntil(T: 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(K: 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(objcKey: 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
2148 ConsumeAnyToken();
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(Other&: 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()) {
2180 SkipMalformedDecl();
2181 return nullptr;
2182 }
2183
2184 if (getLangOpts().HLSL)
2185 while (MaybeParseHLSLAnnotations(D))
2186 ;
2187
2188 if (Tok.is(K: 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, LateAttrs: &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(K: tok::kw__Noreturn)) {
2202 SourceLocation Loc = ConsumeToken();
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, LateAttrs: &LateParsedAttrs);
2210 Fixit &= Tok.isOneOf(Ks: tok::semi, Ks: tok::l_brace, Ks: tok::kw_try);
2211
2212 Diag(Loc, DiagID: diag::err_c11_noreturn_misplaced)
2213 << (Fixit ? FixItHint::CreateRemoval(RemoveRange: Loc) : FixItHint())
2214 << (Fixit ? FixItHint::CreateInsertion(InsertionLoc: D.getBeginLoc(), Code: "_Noreturn ")
2215 : FixItHint());
2216 }
2217
2218 // Check to see if we have a function *definition* which must have a body.
2219 if (Tok.is(K: tok::equal) && NextToken().is(K: 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, DiagID: diag::err_virt_specifier_outside_class)
2232 << VirtSpecifiers::getSpecifierName(VS: Specifier)
2233 << FixItHint::CreateRemoval(RemoveRange: 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(Declarator: 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.
2250 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
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.
2254 Diag(Loc: DS.getStorageClassSpecLoc(),
2255 DiagID: diag::err_function_declared_typedef)
2256 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
2257 DS.ClearStorageClassSpecs();
2258 }
2259 Decl *TheDecl = nullptr;
2260
2261 if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation) {
2262 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2263 // If the declarator-id is not a template-id, issue a diagnostic
2264 // and recover by ignoring the 'template' keyword.
2265 Diag(Tok, DiagID: diag::err_template_defn_explicit_instantiation) << 0;
2266 TheDecl = ParseFunctionDefinition(D, TemplateInfo: ParsedTemplateInfo(),
2267 LateParsedAttrs: &LateParsedAttrs);
2268 } else {
2269 SourceLocation LAngleLoc =
2270 PP.getLocForEndOfToken(Loc: TemplateInfo.TemplateLoc);
2271 Diag(Loc: D.getIdentifierLoc(),
2272 DiagID: diag::err_explicit_instantiation_with_definition)
2273 << SourceRange(TemplateInfo.TemplateLoc)
2274 << FixItHint::CreateInsertion(InsertionLoc: LAngleLoc, Code: "<>");
2275
2276 // Recover as if it were an explicit specialization.
2277 TemplateParameterLists FakedParamLists;
2278 FakedParamLists.push_back(Elt: Actions.ActOnTemplateParameterList(
2279 Depth: 0, ExportLoc: SourceLocation(), TemplateLoc: TemplateInfo.TemplateLoc, LAngleLoc, Params: {},
2280 RAngleLoc: LAngleLoc, RequiresClause: nullptr));
2281
2282 TheDecl = ParseFunctionDefinition(
2283 D,
2284 TemplateInfo: ParsedTemplateInfo(&FakedParamLists,
2285 /*isSpecialization=*/true,
2286 /*lastParameterListWasEmpty=*/true),
2287 LateParsedAttrs: &LateParsedAttrs);
2288 }
2289 } else {
2290 TheDecl =
2291 ParseFunctionDefinition(D, TemplateInfo, LateParsedAttrs: &LateParsedAttrs);
2292 }
2293
2294 return Actions.ConvertDeclToDeclGroup(Ptr: TheDecl);
2295 }
2296
2297 if (isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No) ||
2298 Tok.is(K: 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, DiagID: diag::err_expected_fn_body);
2309 SkipUntil(T: tok::semi);
2310 return nullptr;
2311 }
2312 } else {
2313 if (Tok.is(K: tok::l_brace)) {
2314 Diag(Tok, DiagID: diag::err_function_definition_not_allowed);
2315 SkipMalformedDecl();
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(K: tok::colon) || isTokIdentifier_in())) {
2332 bool IsForRangeLoop = false;
2333 if (TryConsumeToken(Expected: tok::colon, Loc&: FRI->ColonLoc)) {
2334 IsForRangeLoop = true;
2335 EnterExpressionEvaluationContext ForRangeInitContext(
2336 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
2337 /*LambdaContextDecl=*/nullptr,
2338 Sema::ExpressionEvaluationContextRecord::EK_Other,
2339 getLangOpts().CPlusPlus23);
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(K: tok::l_brace))
2351 FRI->RangeExpr = ParseBraceInitializer();
2352 else
2353 FRI->RangeExpr = ParseExpression();
2354
2355 // Before c++23, ForRangeLifetimeExtendTemps should be empty.
2356 assert(
2357 getLangOpts().CPlusPlus23 ||
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(S: getCurScope(), D);
2367 if (IsForRangeLoop) {
2368 Actions.ActOnCXXForRangeDecl(D: ThisDecl);
2369 } else {
2370 // Obj-C for loop
2371 if (auto *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl))
2372 VD->setObjCForDecl(true);
2373 }
2374 Actions.FinalizeDeclaration(D: ThisDecl);
2375 D.complete(D: ThisDecl);
2376 return Actions.FinalizeDeclaratorGroup(S: getCurScope(), DS, Group: ThisDecl);
2377 }
2378
2379 SmallVector<Decl *, 8> DeclsInGroup;
2380 Decl *FirstDecl =
2381 ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo, FRI);
2382 if (LateParsedAttrs.size() > 0)
2383 ParseLexedAttributeList(LAs&: LateParsedAttrs, D: FirstDecl, EnterScope: true, OnDefinition: false);
2384 D.complete(D: FirstDecl);
2385 if (FirstDecl)
2386 DeclsInGroup.push_back(Elt: 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(Expected: tok::comma, Loc&: 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(Loc: CommaLoc, DiagID: diag::err_expected_semi_declaration)
2399 << FixItHint::CreateReplacement(RemoveRange: CommaLoc, Code: ";");
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(Loc: CommaLoc, DiagID: 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(K: tok::kw_requires))
2442 ParseTrailingRequiresClauseWithScope(D);
2443 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D, TemplateInfo);
2444 D.complete(D: ThisDecl);
2445 if (ThisDecl)
2446 DeclsInGroup.push_back(Elt: ThisDecl);
2447 }
2448 }
2449
2450 if (DeclEnd)
2451 *DeclEnd = Tok.getLocation();
2452
2453 if (ExpectSemi && ExpectAndConsumeSemi(
2454 DiagID: 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(AllowImplicitTypename: ImplicitTypenameContext::No))
2461 SkipMalformedDecl();
2462 }
2463
2464 return Actions.FinalizeDeclaratorGroup(S: getCurScope(), DS, Group: DeclsInGroup);
2465}
2466
2467bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2468 // If a simple-asm-expr is present, parse it.
2469 if (Tok.is(K: tok::kw_asm)) {
2470 SourceLocation Loc;
2471 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, EndLoc: &Loc));
2472 if (AsmLabel.isInvalid()) {
2473 SkipUntil(T: tok::semi, Flags: 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(ScopeFlags: 0);
2508 S = P.getCurScope();
2509 }
2510 if (ThisDecl && !ThisDecl->isInvalidDecl()) {
2511 P.Actions.ActOnCXXEnterDeclInitializer(S, Dcl: 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, Dcl: 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(K: tok::l_paren))
2537 TheInitKind = InitKind::CXXDirect;
2538 else if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::l_brace) &&
2539 (!CurParsedObjCImpl || !D.isFunctionDeclarator()))
2540 TheInitKind = InitKind::CXXBraced;
2541 else
2542 TheInitKind = InitKind::Uninitialized;
2543 if (TheInitKind != InitKind::Uninitialized)
2544 D.setHasInitializer();
2545
2546 // Inform Sema that we just parsed this declarator.
2547 Decl *ThisDecl = nullptr;
2548 Decl *OuterDecl = nullptr;
2549 switch (TemplateInfo.Kind) {
2550 case ParsedTemplateKind::NonTemplate:
2551 ThisDecl = Actions.ActOnDeclarator(S: getCurScope(), D);
2552 break;
2553
2554 case ParsedTemplateKind::Template:
2555 case ParsedTemplateKind::ExplicitSpecialization: {
2556 ThisDecl = Actions.ActOnTemplateDeclarator(S: getCurScope(),
2557 TemplateParameterLists: *TemplateInfo.TemplateParams,
2558 D);
2559 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(Val: 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 }
2567 case ParsedTemplateKind::ExplicitInstantiation: {
2568 if (Tok.is(K: tok::semi)) {
2569 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2570 S: getCurScope(), ExternLoc: TemplateInfo.ExternLoc, TemplateLoc: TemplateInfo.TemplateLoc, D);
2571 if (ThisRes.isInvalid()) {
2572 SkipUntil(T: tok::semi, Flags: 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
2580 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2581 // If the declarator-id is not a template-id, issue a diagnostic and
2582 // recover by ignoring the 'template' keyword.
2583 Diag(Tok, DiagID: diag::err_template_defn_explicit_instantiation)
2584 << 2 << FixItHint::CreateRemoval(RemoveRange: TemplateInfo.TemplateLoc);
2585 ThisDecl = Actions.ActOnDeclarator(S: getCurScope(), D);
2586 } else {
2587 SourceLocation LAngleLoc =
2588 PP.getLocForEndOfToken(Loc: TemplateInfo.TemplateLoc);
2589 Diag(Loc: D.getIdentifierLoc(),
2590 DiagID: diag::err_explicit_instantiation_with_definition)
2591 << SourceRange(TemplateInfo.TemplateLoc)
2592 << FixItHint::CreateInsertion(InsertionLoc: LAngleLoc, Code: "<>");
2593
2594 // Recover as if it were an explicit specialization.
2595 TemplateParameterLists FakedParamLists;
2596 FakedParamLists.push_back(Elt: Actions.ActOnTemplateParameterList(
2597 Depth: 0, ExportLoc: SourceLocation(), TemplateLoc: TemplateInfo.TemplateLoc, LAngleLoc, Params: {},
2598 RAngleLoc: LAngleLoc, RequiresClause: nullptr));
2599
2600 ThisDecl =
2601 Actions.ActOnTemplateDeclarator(S: getCurScope(), TemplateParameterLists: FakedParamLists, D);
2602 }
2603 }
2604 break;
2605 }
2606 }
2607
2608 SemaCUDA::CUDATargetContextRAII X(Actions.CUDA(),
2609 SemaCUDA::CTCK_InitGlobalVar, ThisDecl);
2610 switch (TheInitKind) {
2611 // Parse declarator '=' initializer.
2612 case InitKind::Equal: {
2613 SourceLocation EqualLoc = ConsumeToken();
2614
2615 if (Tok.is(K: tok::kw_delete)) {
2616 if (D.isFunctionDeclarator())
2617 Diag(Loc: ConsumeToken(), DiagID: diag::err_default_delete_in_multiple_declaration)
2618 << 1 /* delete */;
2619 else
2620 Diag(Loc: ConsumeToken(), DiagID: diag::err_deleted_non_function);
2621 SkipDeletedFunctionBody();
2622 } else if (Tok.is(K: tok::kw_default)) {
2623 if (D.isFunctionDeclarator())
2624 Diag(Loc: ConsumeToken(), DiagID: diag::err_default_delete_in_multiple_declaration)
2625 << 0 /* default */;
2626 else
2627 Diag(Loc: ConsumeToken(), DiagID: diag::err_default_special_members)
2628 << getLangOpts().CPlusPlus20;
2629 } else {
2630 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2631
2632 if (Tok.is(K: tok::code_completion)) {
2633 cutOffParsing();
2634 Actions.CodeCompletion().CodeCompleteInitializer(S: getCurScope(),
2635 D: ThisDecl);
2636 Actions.FinalizeDeclaration(D: ThisDecl);
2637 return nullptr;
2638 }
2639
2640 PreferredType.enterVariableInit(Tok: Tok.getLocation(), D: ThisDecl);
2641 ExprResult Init = ParseInitializer(DeclForInitializer: 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(K: tok::r_paren) && FRI && D.isFirstDeclarator()) {
2646 Diag(Loc: EqualLoc, DiagID: diag::err_single_decl_assign_in_for_range)
2647 << FixItHint::CreateReplacement(RemoveRange: EqualLoc, Code: ":");
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()) {
2656 SmallVector<tok::TokenKind, 2> StopTokens;
2657 StopTokens.push_back(Elt: tok::comma);
2658 if (D.getContext() == DeclaratorContext::ForInit ||
2659 D.getContext() == DeclaratorContext::SelectionInit)
2660 StopTokens.push_back(Elt: tok::r_paren);
2661 SkipUntil(Toks: StopTokens, Flags: StopAtSemi | StopBeforeMatch);
2662 Actions.ActOnInitializerError(Dcl: ThisDecl);
2663 } else
2664 Actions.AddInitializerToDecl(dcl: ThisDecl, init: 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>(Val: ThisDecl);
2679 auto RunSignatureHelp = [&]() {
2680 QualType PreferredType =
2681 Actions.CodeCompletion().ProduceConstructorSignatureHelp(
2682 Type: ThisVarDecl->getType()->getCanonicalTypeInternal(),
2683 Loc: ThisDecl->getLocation(), Args: Exprs, OpenParLoc: T.getOpenLocation(),
2684 /*Braced=*/false);
2685 CalledSignatureHelp = true;
2686 return PreferredType;
2687 };
2688 auto SetPreferredType = [&] {
2689 PreferredType.enterFunctionArgument(Tok: Tok.getLocation(), ComputeType: 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 Type: ThisVarDecl->getType()->getCanonicalTypeInternal(),
2707 Loc: ThisDecl->getLocation(), Args: Exprs, OpenParLoc: T.getOpenLocation(),
2708 /*Braced=*/false);
2709 CalledSignatureHelp = true;
2710 }
2711 Actions.ActOnInitializerError(Dcl: ThisDecl);
2712 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
2713 } else {
2714 // Match the ')'.
2715 T.consumeClose();
2716
2717 ExprResult Initializer = Actions.ActOnParenListExpr(L: T.getOpenLocation(),
2718 R: T.getCloseLocation(),
2719 Val: Exprs);
2720 Actions.AddInitializerToDecl(dcl: ThisDecl, init: Initializer.get(),
2721 /*DirectInit=*/true);
2722 }
2723 break;
2724 }
2725 case InitKind::CXXBraced: {
2726 // Parse C++0x braced-init-list.
2727 Diag(Tok, DiagID: diag::warn_cxx98_compat_generalized_initializer_lists);
2728
2729 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2730
2731 PreferredType.enterVariableInit(Tok: Tok.getLocation(), D: ThisDecl);
2732 ExprResult Init(ParseBraceInitializer());
2733
2734 if (Init.isInvalid()) {
2735 Actions.ActOnInitializerError(Dcl: ThisDecl);
2736 } else
2737 Actions.AddInitializerToDecl(dcl: ThisDecl, init: Init.get(), /*DirectInit=*/true);
2738 break;
2739 }
2740 case InitKind::Uninitialized: {
2741 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2742 Actions.ActOnUninitializedDecl(dcl: ThisDecl);
2743 break;
2744 }
2745 }
2746
2747 Actions.FinalizeDeclaration(D: 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, LateAttrs: nullptr,
2759 AllowImplicitTypename);
2760
2761 // Validate declspec for type-name.
2762 unsigned Specs = DS.getParsedSpecifiers();
2763 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2764 Diag(Tok, DiagID: diag::err_expected_type);
2765 DS.SetTypeSpecError();
2766 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2767 Diag(Tok, DiagID: diag::err_typename_requires_specqual);
2768 if (!DS.hasTypeSpecifier())
2769 DS.SetTypeSpecError();
2770 }
2771
2772 // Issue diagnostic and remove storage class if present.
2773 if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2774 if (DS.getStorageClassSpecLoc().isValid())
2775 Diag(Loc: DS.getStorageClassSpecLoc(),DiagID: diag::err_typename_invalid_storageclass);
2776 else
2777 Diag(Loc: DS.getThreadStorageClassSpecLoc(),
2778 DiagID: diag::err_typename_invalid_storageclass);
2779 DS.ClearStorageClassSpecs();
2780 }
2781
2782 // Issue diagnostic and remove function specifier if present.
2783 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2784 if (DS.isInlineSpecified())
2785 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_typename_invalid_functionspec);
2786 if (DS.isVirtualSpecified())
2787 Diag(Loc: DS.getVirtualSpecLoc(), DiagID: diag::err_typename_invalid_functionspec);
2788 if (DS.hasExplicitSpecifier())
2789 Diag(Loc: DS.getExplicitSpecLoc(), DiagID: diag::err_typename_invalid_functionspec);
2790 if (DS.isNoreturnSpecified())
2791 Diag(Loc: DS.getNoreturnSpecLoc(), DiagID: 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(Loc: DS.getConstexprSpecLoc(), DiagID: 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///
2821static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2822 return T.isOneOf(Ks: tok::l_square, Ks: tok::l_paren, Ks: tok::r_paren, Ks: tok::semi,
2823 Ks: tok::comma, Ks: tok::equal, Ks: tok::kw_asm, Ks: tok::l_brace,
2824 Ks: 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() &&
2854 isValidAfterIdentifierInDeclarator(T: NextToken())) {
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 &&
2867 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
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&: *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 II: *Tok.getIdentifierInfo(), NameLoc: Tok.getLocation(),
2882 IsTemplateTypeArg: DSC == DeclSpecContext::DSC_template_type_arg)) {
2883 const char *PrevSpec;
2884 unsigned DiagID;
2885 DS.SetTypeSpecType(T: DeclSpec::TST_typename, Loc, PrevSpec, DiagID, Rep: T,
2886 Policy: 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(II&: *Tok.getIdentifierInfo(), S: getCurScope())) {
2904 default: break;
2905 case DeclSpec::TST_enum:
2906 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2907 case DeclSpec::TST_union:
2908 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2909 case DeclSpec::TST_struct:
2910 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2911 case DeclSpec::TST_interface:
2912 TagName="__interface"; FixitTagName = "__interface ";
2913 TagKind=tok::kw___interface;break;
2914 case DeclSpec::TST_class:
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(),
2921 Sema::LookupOrdinaryName);
2922
2923 Diag(Loc, DiagID: diag::err_use_of_tag_name_without_tag)
2924 << TokenName << TagName << getLangOpts().CPlusPlus
2925 << FixItHint::CreateInsertion(InsertionLoc: Tok.getLocation(), Code: FixitTagName);
2926
2927 if (Actions.LookupName(R, S: getCurScope())) {
2928 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2929 I != IEnd; ++I)
2930 Diag(Loc: (*I)->getLocation(), DiagID: 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(TagLoc: Loc, DS, TemplateInfo, AS,
2937 DSC: DeclSpecContext::DSC_normal);
2938 else
2939 ParseClassSpecifier(TagTokKind: TagKind, TagLoc: Loc, DS, TemplateInfo, AS,
2940 /*EnteringContext*/ false,
2941 DSC: DeclSpecContext::DSC_normal, Attributes&: 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, DiagID: diag::err_constructor_bad_name)
2978 << Tok.getIdentifierInfo() << II
2979 << FixItHint::CreateReplacement(RemoveRange: Tok.getLocation(), Code: 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&: *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(K: tok::less);
3014 Actions.DiagnoseUnknownTypeName(II, IILoc: Loc, S: getCurScope(), SS, SuggestedType&: 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(T: DeclSpec::TST_typename, Loc, PrevSpec, DiagID, Rep: T,
3023 Policy: 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(ConsumeLastToken: true, LAngleLoc&: LAngle, TemplateArgs&: Args, RAngleLoc&: 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) {
3056 case DeclaratorContext::Member:
3057 return DeclSpecContext::DSC_class;
3058 case DeclaratorContext::File:
3059 return DeclSpecContext::DSC_top_level;
3060 case DeclaratorContext::TemplateParam:
3061 return DeclSpecContext::DSC_template_param;
3062 case DeclaratorContext::TemplateArg:
3063 return DeclSpecContext::DSC_template_arg;
3064 case DeclaratorContext::TemplateTypeArg:
3065 return DeclSpecContext::DSC_template_type_arg;
3066 case DeclaratorContext::TrailingReturn:
3067 case DeclaratorContext::TrailingReturnVar:
3068 return DeclSpecContext::DSC_trailing;
3069 case DeclaratorContext::AliasDecl:
3070 case DeclaratorContext::AliasTemplate:
3071 return DeclSpecContext::DSC_alias_declaration;
3072 case DeclaratorContext::Association:
3073 return DeclSpecContext::DSC_association;
3074 case DeclaratorContext::TypeName:
3075 return DeclSpecContext::DSC_type_specifier;
3076 case DeclaratorContext::Condition:
3077 return DeclSpecContext::DSC_condition;
3078 case DeclaratorContext::ConversionId:
3079 return DeclSpecContext::DSC_conv_operator;
3080 case DeclaratorContext::CXXNew:
3081 return DeclSpecContext::DSC_new;
3082 case DeclaratorContext::Prototype:
3083 case DeclaratorContext::ObjCResult:
3084 case DeclaratorContext::ObjCParameter:
3085 case DeclaratorContext::KNRTypeList:
3086 case DeclaratorContext::FunctionalCast:
3087 case DeclaratorContext::Block:
3088 case DeclaratorContext::ForInit:
3089 case DeclaratorContext::SelectionInit:
3090 case DeclaratorContext::CXXCatch:
3091 case DeclaratorContext::ObjCCatch:
3092 case DeclaratorContext::BlockLiteral:
3093 case DeclaratorContext::LambdaExpr:
3094 case DeclaratorContext::LambdaExprParameter:
3095 case DeclaratorContext::RequiresExpr:
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,
3104 ParsedType &TypeResult) {
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, OpLoc: TypeLoc, R: TypeRange))
3111 return ExprError();
3112 TypeResult = Ty;
3113 IsType = true;
3114 } else {
3115 ER = ParseConstantExpression();
3116 IsType = false;
3117 }
3118
3119 if (getLangOpts().CPlusPlus11)
3120 TryConsumeToken(Expected: tok::ellipsis, Loc&: 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;
3139 ParsedType TypeResult;
3140 SourceLocation EllipsisLoc;
3141 ExprResult ArgExpr =
3142 ParseAlignArgument(KWName: PP.getSpelling(Tok: KWTok), Start: 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(attrName: KWName, attrRange: KWLoc, scope: AttributeScopeInfo(), typeArg: TypeResult, formUsed: Kind,
3155 ellipsisLoc: EllipsisLoc);
3156 } else {
3157 ArgsVector ArgExprs;
3158 ArgExprs.push_back(Elt: ArgExpr.get());
3159 Attrs.addNew(attrName: KWName, attrRange: KWLoc, scope: AttributeScopeInfo(), args: ArgExprs.data(), numArgs: 1, form: Kind,
3160 ellipsisLoc: 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(D: 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 {
3189 ExprResult ER = ParseAssignmentExpression();
3190 if (ER.isInvalid()) {
3191 T.skipToEnd();
3192 return;
3193 }
3194 ArgExprs.push_back(Elt: ER.get());
3195 } while (TryConsumeToken(Expected: tok::comma));
3196
3197 T.consumeClose();
3198 SourceLocation EndLoc = T.getCloseLocation();
3199
3200 if (ArgExprs.empty() || ArgExprs.size() > 3) {
3201 Diag(Loc: KwLoc, DiagID: diag::err_ptrauth_qualifier_bad_arg_count);
3202 return;
3203 }
3204
3205 Attrs.addNew(attrName: KwName, attrRange: SourceRange(KwLoc, EndLoc), scope: AttributeScopeInfo(),
3206 args: ArgExprs.data(), numArgs: ArgExprs.size(),
3207 form: ParsedAttr::Form::Keyword(/*IsAlignAs=*/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(K: tok::r_paren)) {
3223 Diag(Loc: Tok.getLocation(), DiagID: 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 =
3231 Sema::ExpressionEvaluationContextRecord::ExpressionKind;
3232 EnterExpressionEvaluationContext EC(
3233 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, nullptr,
3234 ExpressionKind::EK_AttrArgument);
3235
3236 ExprResult ArgExpr = ParseAssignmentExpression();
3237 if (ArgExpr.isInvalid()) {
3238 Parens.skipToEnd();
3239 return;
3240 }
3241
3242 ArgExprs.push_back(Elt: ArgExpr.get());
3243 Parens.consumeClose();
3244
3245 ASTContext &Ctx = Actions.getASTContext();
3246
3247 ArgExprs.push_back(Elt: IntegerLiteral::Create(
3248 C: Ctx, V: llvm::APInt(Ctx.getTypeSize(T: Ctx.getSizeType()), 0),
3249 type: Ctx.getSizeType(), l: SourceLocation()));
3250
3251 Attrs.addNew(attrName: &AttrName, attrRange: SourceRange(AttrNameLoc, Parens.getCloseLocation()),
3252 scope: AttributeScopeInfo(), args: ArgExprs.data(), numArgs: ArgExprs.size(), form: 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
3264 ExprResult ER = ParseConstantExpression();
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(Ks: tok::identifier, Ks: tok::coloncolon, Ks: tok::kw_decltype,
3286 Ks: tok::annot_template_id) &&
3287 TryAnnotateCXXScopeToken(EnteringContext)) {
3288 SkipMalformedDecl();
3289 return true;
3290 }
3291
3292 bool HasScope = Tok.is(K: 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(Ks: tok::kw_typename, Ks: tok::annot_typename)) {
3300 // A declarator-id can't start with 'typename'.
3301 MightBeDeclarator = false;
3302 } else if (AfterScope.is(K: 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(K: tok::identifier)) {
3310 const Token &Next = HasScope ? GetLookAheadToken(N: 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(Ks: tok::star, Ks: tok::amp, Ks: tok::ampamp, Ks: tok::identifier,
3315 Ks: tok::annot_cxxscope, Ks: 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 Annotation: Tok.getAnnotationValue(), AnnotationRange: Tok.getAnnotationRange(), SS);
3325 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
3326 Sema::NameClassification Classification = Actions.ClassifyName(
3327 S: getCurScope(), SS, Name, NameLoc: AfterScope.getLocation(), NextToken: Next,
3328 /*CCC=*/nullptr);
3329 switch (Classification.getKind()) {
3330 case NameClassificationKind::Error:
3331 SkipMalformedDecl();
3332 return true;
3333
3334 case NameClassificationKind::Keyword:
3335 llvm_unreachable("typo correction is not possible here");
3336
3337 case NameClassificationKind::Type:
3338 case NameClassificationKind::TypeTemplate:
3339 case NameClassificationKind::UndeclaredNonType:
3340 case NameClassificationKind::UndeclaredTemplate:
3341 case NameClassificationKind::Concept:
3342 // Not a previously-declared non-type entity.
3343 MightBeDeclarator = false;
3344 break;
3345
3346 case NameClassificationKind::Unknown:
3347 case NameClassificationKind::NonType:
3348 case NameClassificationKind::DependentNonType:
3349 case NameClassificationKind::OverloadSet:
3350 case NameClassificationKind::VarTemplate:
3351 case NameClassificationKind::FunctionTemplate:
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(Loc: PP.getLocForEndOfToken(Loc: DS.getRepAsDecl()->getEndLoc()),
3363 DiagID: diag::err_expected_after)
3364 << DeclSpec::getSpecifierName(T: DS.getTypeSpecType(), Policy: 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, TemplateInfo&: NotATemplate, AS, DSC: 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(K: tok::kw__Atomic) &&
3420 DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3421 !DS.hasTypeSpecifier() && GetLookAheadToken(N: 1).is(K: 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, LO: getLangOpts())) {
3431 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3432 Tok.setKind(tok::identifier);
3433 return false;
3434 }
3435 isInvalid = DS.SetTypeSpecType(T: 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&: 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(Loc: PA.getLoc(), DiagID: 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(Loc: PA.getLoc(), DiagID: diag::err_attribute_wrong_decl_type)
3479 << PA << PA.isRegularKeywordAttribute()
3480 << ExpectedParameterOrImplicitObjectParameter;
3481 else
3482 Diag(Loc: PA.getLoc(), DiagID: diag::err_attribute_not_type_attr)
3483 << PA << PA.isRegularKeywordAttribute();
3484 PA.setInvalid();
3485 }
3486
3487 DS.takeAttributesAppendingingFrom(attrs);
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(S&: 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, DiagID: diag::warn_c23_compat_keyword) << Tok.getName();
3507 ParseAlignmentSpecifier(Attrs&: DS.getAttributes());
3508 continue;
3509 }
3510 [[fallthrough]];
3511 case tok::l_square:
3512 if (!isAllowedCXX11AttributeSpecifier())
3513 goto DoneWithDeclSpec;
3514
3515 Attribute:
3516 ProhibitAttributes(Attrs&: 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: {
3528 SemaCodeCompletion::ParserCompletionContext CCC =
3529 SemaCodeCompletion::PCC_Namespace;
3530 if (DS.hasTypeSpecifier()) {
3531 bool AllowNonIdentifiers
3532 = (getCurScope()->getFlags() & (Scope::ControlScope |
3533 Scope::BlockScope |
3534 Scope::TemplateParamScope |
3535 Scope::FunctionPrototypeScope |
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 S: 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
3550 ? SemaCodeCompletion::PCC_MemberTemplate
3551 : SemaCodeCompletion::PCC_Template;
3552 else if (DSContext == DeclSpecContext::DSC_class)
3553 CCC = SemaCodeCompletion::PCC_Class;
3554 else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3555 CCC = SemaCodeCompletion::PCC_LocalDeclarationSpecifiers;
3556 else if (CurParsedObjCImpl)
3557 CCC = SemaCodeCompletion::PCC_ObjCImplementation;
3558
3559 cutOffParsing();
3560 Actions.CodeCompletion().CodeCompleteOrdinaryName(S: getCurScope(), CompletionContext: 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(K: 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(Annotation: Tok.getAnnotationValue(),
3584 AnnotationRange: Tok.getAnnotationRange(),
3585 SS);
3586
3587 // We are looking for a qualified typename.
3588 Token Next = NextToken();
3589
3590 TemplateIdAnnotation *TemplateId = Next.is(K: tok::annot_template_id)
3591 ? takeTemplateIdAnnotation(tok: 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(II: *TemplateId->Name, S: getCurScope(), SS: &SS) &&
3615 isConstructorDeclarator(/*Unqualified=*/false,
3616 /*DeductionGuide=*/false,
3617 IsFriend: 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(K: tok::annot_typename)) {
3644 DS.getTypeSpecScope() = SS;
3645 ConsumeAnnotationToken(); // The C++ scope.
3646 TypeResult T = getTypeAnnotation(Tok);
3647 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_typename,
3648 Loc: Tok.getAnnotationEndLoc(),
3649 PrevSpec, DiagID, Rep: 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(K: 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(K: 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(II: *Next.getIdentifierInfo(), S: getCurScope(),
3675 SS: &SS) &&
3676 isConstructorDeclarator(/*Unqualified=*/false,
3677 /*DeductionGuide=*/false,
3678 IsFriend: DS.isFriendSpecified(),
3679 TemplateInfo: &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 II: *Next.getIdentifierInfo(), NameLoc: Next.getLocation(), S: getCurScope(), SS: &SS,
3690 isClassName: false, HasTrailingDot: false, ObjectType: nullptr,
3691 /*IsCtorOrDtorName=*/false,
3692 /*WantNontrivialTypeSourceInfo=*/true,
3693 IsClassTemplateDeductionContext: isClassTemplateDeductionContext(DSC: 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(K: tok::annot_cxxscope) ||
3706 NextToken().isNot(K: 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: &SS, TemplateInfo, AS, DSC: DSContext, Attrs)) {
3712 if (!Attrs.empty()) {
3713 AttrsLastTime = true;
3714 attrs.takeAllAppendingFrom(Other&: Attrs);
3715 }
3716 continue;
3717 }
3718 goto DoneWithDeclSpec;
3719 }
3720
3721 DS.getTypeSpecScope() = SS;
3722 ConsumeAnnotationToken(); // The C++ scope.
3723
3724 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_typename, Loc, PrevSpec,
3725 DiagID, Rep: 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
3741 TypeResult T = getTypeAnnotation(Tok);
3742 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_typename, Loc, PrevSpec,
3743 DiagID, Rep: 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 &&
3763 DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3764 DS.getStorageClassSpec() == DeclSpec::SCS_static)
3765 TryKeywordIdentFallback(DisableKeyword: 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(K: tok::identifier) &&
3786 Tok.getIdentifierInfo()->getName() == "__declspec") {
3787 Diag(Loc, DiagID: 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(K: 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(K: 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);
3844 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_typename, Loc, PrevSpec,
3845 DiagID, Rep: 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(II: *Tok.getIdentifierInfo(), S: getCurScope()) &&
3858 isConstructorDeclarator(/*Unqualified=*/true,
3859 /*DeductionGuide=*/false,
3860 IsFriend: DS.isFriendSpecified()))
3861 goto DoneWithDeclSpec;
3862
3863 ParsedType TypeRep = Actions.getTypeName(
3864 II: *Tok.getIdentifierInfo(), NameLoc: Tok.getLocation(), S: getCurScope(), SS: nullptr,
3865 isClassName: false, HasTrailingDot: false, ObjectType: nullptr, IsCtorOrDtorName: false, WantNontrivialTypeSourceInfo: false,
3866 IsClassTemplateDeductionContext: isClassTemplateDeductionContext(DSC: 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(K: tok::identifier))
3874 continue;
3875 ParsedAttributes Attrs(AttrFactory);
3876 if (ParseImplicitInt(DS, SS: nullptr, TemplateInfo, AS, DSC: DSContext, Attrs)) {
3877 if (!Attrs.empty()) {
3878 AttrsLastTime = true;
3879 attrs.takeAllAppendingFrom(Other&: 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(S: getCurScope(), Name: *Tok.getIdentifierInfo(),
3893 NameLoc: Tok.getLocation(), SS) &&
3894 isConstructorDeclarator(/*Unqualified*/ true,
3895 /*DeductionGuide*/ true))
3896 goto DoneWithDeclSpec;
3897
3898 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_typename, Loc, PrevSpec,
3899 DiagID, Rep: 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(K: tok::less) && getLangOpts().ObjC) {
3910 SourceLocation NewEndLoc;
3911 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3912 loc: Loc, type: TypeRep, /*consumeLastToken=*/true,
3913 endLoc&: NewEndLoc);
3914 if (NewTypeRep.isUsable()) {
3915 DS.UpdateTypeRep(Rep: 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: 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(Ks: tok::identifier, Ks: tok::kw_const,
3946 Ks: tok::kw_volatile, Ks: tok::kw_restrict, Ks: tok::amp,
3947 Ks: tok::ampamp)) {
3948 Diag(Loc, DiagID: diag::err_placeholder_expected_auto_or_decltype_auto)
3949 << FixItHint::CreateInsertion(InsertionLoc: NextToken().getLocation(), Code: "auto");
3950 // Attempt to continue as if 'auto' was placed here.
3951 isInvalid = DS.SetTypeSpecType(T: TST_auto, Loc, PrevSpec, DiagID,
3952 Rep: TemplateId, Policy);
3953 break;
3954 }
3955 if (!NextToken().isOneOf(Ks: tok::kw_auto, Ks: tok::kw_decltype))
3956 goto DoneWithDeclSpec;
3957
3958 if (TemplateId && !isInvalid && Actions.CheckTypeConstraint(TypeConstraint: TemplateId))
3959 TemplateId = nullptr;
3960
3961 ConsumeAnnotationToken();
3962 SourceLocation AutoLoc = Tok.getLocation();
3963 if (TryConsumeToken(Expected: 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, DiagID: diag::err_expected) << tok::l_paren;
3968 } else {
3969 if (!TryConsumeToken(Expected: tok::kw_auto)) {
3970 // Something like `void foo(Iterator decltype(int) i)`
3971 Tracker.skipToEnd();
3972 Diag(Tok, DiagID: diag::err_placeholder_expected_auto_or_decltype_auto)
3973 << FixItHint::CreateReplacement(RemoveRange: SourceRange(AutoLoc,
3974 Tok.getLocation()),
3975 Code: "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(T: TST_decltype_auto, Loc, PrevSpec,
3985 DiagID, Rep: TemplateId, Policy);
3986 } else {
3987 isInvalid = DS.SetTypeSpecType(T: TST_auto, Loc: AutoLoc, PrevSpec, DiagID,
3988 Rep: 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(II: *TemplateId->Name, S: getCurScope()) &&
4005 isConstructorDeclarator(/*Unqualified=*/true,
4006 /*DeductionGuide=*/false,
4007 IsFriend: 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(WhichAttrKinds: PAKM_GNU | PAKM_Declspec, Attrs&: 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: AttrName, attrRange: AttrNameLoc, scope: AttributeScopeInfo(),
4029 args: nullptr, numArgs: 0, form: tok::kw___forceinline);
4030 break;
4031 }
4032
4033 case tok::kw___unaligned:
4034 isInvalid = DS.SetTypeQual(T: DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
4035 Lang: getLangOpts());
4036 break;
4037
4038 // __ptrauth qualifier.
4039 case tok::kw___ptrauth:
4040 ParsePtrauthQualifier(Attrs&: 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(attrs&: DS.getAttributes());
4055 continue;
4056
4057 case tok::kw___funcref:
4058 ParseWebAssemblyFuncrefTypeAttribute(attrs&: DS.getAttributes());
4059 continue;
4060
4061 // Borland single token adornments.
4062 case tok::kw___pascal:
4063 ParseBorlandTypeAttributes(attrs&: DS.getAttributes());
4064 continue;
4065
4066 // OpenCL single token adornments.
4067 case tok::kw___kernel:
4068 ParseOpenCLKernelAttributes(attrs&: DS.getAttributes());
4069 continue;
4070
4071 // CUDA/HIP single token adornments.
4072 case tok::kw___noinline__:
4073 ParseCUDAFunctionAttributes(attrs&: 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(attrs&: DS.getAttributes());
4082 continue;
4083
4084 // Objective-C 'kindof' types.
4085 case tok::kw___kindof:
4086 DS.getAttributes().addNew(attrName: Tok.getIdentifierInfo(), attrRange: Loc,
4087 scope: AttributeScopeInfo(), args: nullptr, numArgs: 0,
4088 form: tok::kw___kindof);
4089 (void)ConsumeToken();
4090 continue;
4091
4092 // storage-class-specifier
4093 case tok::kw_typedef:
4094 isInvalid = DS.SetStorageClassSpec(S&: Actions, SC: DeclSpec::SCS_typedef, Loc,
4095 PrevSpec, DiagID, Policy);
4096 isStorageClass = true;
4097 break;
4098 case tok::kw_extern:
4099 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
4100 Diag(Tok, DiagID: diag::ext_thread_before) << "extern";
4101 isInvalid = DS.SetStorageClassSpec(S&: Actions, SC: DeclSpec::SCS_extern, Loc,
4102 PrevSpec, DiagID, Policy);
4103 isStorageClass = true;
4104 break;
4105 case tok::kw___private_extern__:
4106 isInvalid = DS.SetStorageClassSpec(S&: Actions, SC: DeclSpec::SCS_private_extern,
4107 Loc, PrevSpec, DiagID, Policy);
4108 isStorageClass = true;
4109 break;
4110 case tok::kw_static:
4111 if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
4112 Diag(Tok, DiagID: diag::ext_thread_before) << "static";
4113 isInvalid = DS.SetStorageClassSpec(S&: Actions, SC: DeclSpec::SCS_static, Loc,
4114 PrevSpec, DiagID, Policy);
4115 isStorageClass = true;
4116 break;
4117 case tok::kw_auto:
4118 if (getLangOpts().CPlusPlus11 || getLangOpts().C23) {
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() &&
4124 DS.getTypeSpecType() != DeclSpec::TST_auto)
4125 return true;
4126
4127 unsigned I = 1;
4128 while (true) {
4129 const Token &T = GetLookAheadToken(N: I);
4130 if (isKnownToBeTypeSpecifier(Tok: T))
4131 return true;
4132
4133 if (getLangOpts().C23 && isTypeSpecifierQualifier(Tok: T))
4134 ++I;
4135 else
4136 return false;
4137 }
4138 };
4139
4140 if (MayBeTypeSpecifier()) {
4141 isInvalid = DS.SetStorageClassSpec(S&: Actions, SC: DeclSpec::SCS_auto, Loc,
4142 PrevSpec, DiagID, Policy);
4143 if (!isInvalid && !getLangOpts().C23)
4144 Diag(Tok, DiagID: diag::ext_auto_storage_class)
4145 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
4146 } else
4147 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc, PrevSpec,
4148 DiagID, Policy);
4149 } else
4150 isInvalid = DS.SetStorageClassSpec(S&: Actions, SC: DeclSpec::SCS_auto, Loc,
4151 PrevSpec, DiagID, Policy);
4152 isStorageClass = true;
4153 break;
4154 case tok::kw___auto_type:
4155 Diag(Tok, DiagID: diag::ext_auto_type);
4156 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_auto_type, Loc, PrevSpec,
4157 DiagID, Policy);
4158 break;
4159 case tok::kw_register:
4160 isInvalid = DS.SetStorageClassSpec(S&: Actions, SC: DeclSpec::SCS_register, Loc,
4161 PrevSpec, DiagID, Policy);
4162 isStorageClass = true;
4163 break;
4164 case tok::kw_mutable:
4165 isInvalid = DS.SetStorageClassSpec(S&: Actions, SC: DeclSpec::SCS_mutable, Loc,
4166 PrevSpec, DiagID, Policy);
4167 isStorageClass = true;
4168 break;
4169 case tok::kw___thread:
4170 isInvalid = DS.SetStorageClassSpecThread(TSC: DeclSpec::TSCS___thread, Loc,
4171 PrevSpec, DiagID);
4172 isStorageClass = true;
4173 break;
4174 case tok::kw_thread_local:
4175 if (getLangOpts().C23)
4176 Diag(Tok, DiagID: 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.
4182 isInvalid = DS.SetStorageClassSpecThread(
4183 TSC: getLangOpts().C23 ? DeclSpec::TSCS__Thread_local
4184 : DeclSpec::TSCS_thread_local,
4185 Loc, PrevSpec, DiagID);
4186 isStorageClass = true;
4187 break;
4188 case tok::kw__Thread_local:
4189 diagnoseUseOfC11Keyword(Tok);
4190 isInvalid = DS.SetStorageClassSpecThread(TSC: DeclSpec::TSCS__Thread_local,
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 Ext: "__cl_clang_function_pointers", LO: 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(K: tok::l_paren)) {
4223 if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
4224 Diag(Loc: Tok.getLocation(), DiagID: 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(
4233 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4234
4235 ExplicitExpr = ParseConstantExpressionInExprEvalContext();
4236 ConsumedEnd = Tok.getLocation();
4237 if (ExplicitExpr.isUsable()) {
4238 CloseParenLoc = Tok.getLocation();
4239 Tracker.consumeClose();
4240 ExplicitSpec =
4241 Actions.ActOnExplicitBoolSpecifier(E: ExplicitExpr.get());
4242 } else
4243 Tracker.skipToEnd();
4244 } else {
4245 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_cxx20_compat_explicit_bool);
4246 }
4247 }
4248 isInvalid = DS.setFunctionSpecExplicit(Loc: 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, DiagID: diag::warn_c23_compat_keyword) << Tok.getName();
4280 isInvalid = DS.SetConstexprSpec(ConstexprKind: ConstexprSpecKind::Constexpr, Loc,
4281 PrevSpec, DiagID);
4282 break;
4283 case tok::kw_consteval:
4284 isInvalid = DS.SetConstexprSpec(ConstexprKind: ConstexprSpecKind::Consteval, Loc,
4285 PrevSpec, DiagID);
4286 break;
4287 case tok::kw_constinit:
4288 isInvalid = DS.SetConstexprSpec(ConstexprKind: ConstexprSpecKind::Constinit, Loc,
4289 PrevSpec, DiagID);
4290 break;
4291
4292 // type-specifier
4293 case tok::kw_short:
4294 if (!getLangOpts().NativeInt16Type) {
4295 Diag(Tok, DiagID: diag::err_unknown_typename) << Tok.getName();
4296 DS.SetTypeSpecError();
4297 DS.SetRangeEnd(Tok.getLocation());
4298 ConsumeToken();
4299 goto DoneWithDeclSpec;
4300 }
4301 isInvalid = DS.SetTypeSpecWidth(W: TypeSpecifierWidth::Short, Loc, PrevSpec,
4302 DiagID, Policy);
4303 break;
4304 case tok::kw_long:
4305 if (DS.getTypeSpecWidth() != TypeSpecifierWidth::Long)
4306 isInvalid = DS.SetTypeSpecWidth(W: TypeSpecifierWidth::Long, Loc, PrevSpec,
4307 DiagID, Policy);
4308 else
4309 isInvalid = DS.SetTypeSpecWidth(W: TypeSpecifierWidth::LongLong, Loc,
4310 PrevSpec, DiagID, Policy);
4311 break;
4312 case tok::kw___int64:
4313 isInvalid = DS.SetTypeSpecWidth(W: TypeSpecifierWidth::LongLong, Loc,
4314 PrevSpec, DiagID, Policy);
4315 break;
4316 case tok::kw_signed:
4317 isInvalid =
4318 DS.SetTypeSpecSign(S: TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4319 break;
4320 case tok::kw_unsigned:
4321 isInvalid = DS.SetTypeSpecSign(S: TypeSpecifierSign::Unsigned, Loc, PrevSpec,
4322 DiagID);
4323 break;
4324 case tok::kw__Complex:
4325 if (!getLangOpts().C99)
4326 Diag(Tok, DiagID: diag::ext_c99_feature) << Tok.getName();
4327 isInvalid = DS.SetTypeSpecComplex(C: DeclSpec::TSC_complex, Loc, PrevSpec,
4328 DiagID);
4329 break;
4330 case tok::kw__Imaginary:
4331 if (!getLangOpts().C99)
4332 Diag(Tok, DiagID: diag::ext_c99_feature) << Tok.getName();
4333 isInvalid = DS.SetTypeSpecComplex(C: DeclSpec::TSC_imaginary, Loc, PrevSpec,
4334 DiagID);
4335 break;
4336 case tok::kw_void:
4337 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_void, Loc, PrevSpec,
4338 DiagID, Policy);
4339 break;
4340 case tok::kw_char:
4341 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_char, Loc, PrevSpec,
4342 DiagID, Policy);
4343 break;
4344 case tok::kw_int:
4345 isInvalid = DS.SetTypeSpecType(T: 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(KWLoc: Loc, BitWidth: ER.get(), PrevSpec, DiagID, Policy);
4355 ConsumedEnd = PrevTokLocation;
4356 break;
4357 }
4358 case tok::kw___int128:
4359 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_int128, Loc, PrevSpec,
4360 DiagID, Policy);
4361 break;
4362 case tok::kw_half:
4363 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_half, Loc, PrevSpec,
4364 DiagID, Policy);
4365 break;
4366 case tok::kw___bf16:
4367 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_BFloat16, Loc, PrevSpec,
4368 DiagID, Policy);
4369 break;
4370 case tok::kw_float:
4371 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_float, Loc, PrevSpec,
4372 DiagID, Policy);
4373 break;
4374 case tok::kw_double:
4375 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_double, Loc, PrevSpec,
4376 DiagID, Policy);
4377 break;
4378 case tok::kw__Float16:
4379 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_float16, Loc, PrevSpec,
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(T: 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(T: 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:
4403 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_float128, Loc, PrevSpec,
4404 DiagID, Policy);
4405 break;
4406 case tok::kw___ibm128:
4407 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_ibm128, Loc, PrevSpec,
4408 DiagID, Policy);
4409 break;
4410 case tok::kw_wchar_t:
4411 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_wchar, Loc, PrevSpec,
4412 DiagID, Policy);
4413 break;
4414 case tok::kw_char8_t:
4415 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_char8, Loc, PrevSpec,
4416 DiagID, Policy);
4417 break;
4418 case tok::kw_char16_t:
4419 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_char16, Loc, PrevSpec,
4420 DiagID, Policy);
4421 break;
4422 case tok::kw_char32_t:
4423 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_char32, Loc, PrevSpec,
4424 DiagID, Policy);
4425 break;
4426 case tok::kw_bool:
4427 if (getLangOpts().C23)
4428 Diag(Tok, DiagID: diag::warn_c23_compat_keyword) << Tok.getName();
4429 [[fallthrough]];
4430 case tok::kw__Bool:
4431 if (Tok.is(K: tok::kw__Bool) && !getLangOpts().C99)
4432 Diag(Tok, DiagID: diag::ext_c99_feature) << Tok.getName();
4433
4434 if (Tok.is(K: tok::kw_bool) &&
4435 DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
4436 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
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(T: DeclSpec::TST_bool, Loc, PrevSpec,
4444 DiagID, Policy);
4445 }
4446 break;
4447 case tok::kw__Decimal32:
4448 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_decimal32, Loc, PrevSpec,
4449 DiagID, Policy);
4450 break;
4451 case tok::kw__Decimal64:
4452 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_decimal64, Loc, PrevSpec,
4453 DiagID, Policy);
4454 break;
4455 case tok::kw__Decimal128:
4456 isInvalid = DS.SetTypeSpecType(T: DeclSpec::TST_decimal128, Loc, PrevSpec,
4457 DiagID, Policy);
4458 break;
4459 case tok::kw___vector:
4460 isInvalid = DS.SetTypeAltiVecVector(isAltiVecVector: true, Loc, PrevSpec, DiagID, Policy);
4461 break;
4462 case tok::kw___pixel:
4463 isInvalid = DS.SetTypeAltiVecPixel(isAltiVecPixel: true, Loc, PrevSpec, DiagID, Policy);
4464 break;
4465 case tok::kw___bool:
4466 isInvalid = DS.SetTypeAltiVecBool(isAltiVecBool: 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(isPipe: 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:
4493 isInvalid = DS.SetTypeSpecType(T: TST_unknown_anytype, Loc,
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(TagTokKind: Kind, TagLoc: Loc, DS, TemplateInfo, AS,
4510 EnteringContext, DSC: 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(Other&: Attributes);
4517 }
4518 continue;
4519 }
4520
4521 // enum-specifier:
4522 case tok::kw_enum:
4523 ConsumeToken();
4524 ParseEnumSpecifier(TagLoc: Loc, DS, TemplateInfo, AS, DSC: DSContext);
4525 continue;
4526
4527 // cv-qualifier:
4528 case tok::kw_const:
4529 isInvalid = DS.SetTypeQual(T: DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4530 Lang: getLangOpts());
4531 break;
4532 case tok::kw_volatile:
4533 isInvalid = DS.SetTypeQual(T: DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4534 Lang: getLangOpts());
4535 break;
4536 case tok::kw_restrict:
4537 isInvalid = DS.SetTypeQual(T: DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4538 Lang: getLangOpts());
4539 break;
4540 case tok::kw___ob_wrap:
4541 if (!getLangOpts().OverflowBehaviorTypes) {
4542 Diag(Loc, DiagID: diag::warn_overflow_behavior_keyword_disabled)
4543 << tok::getKeywordSpelling(Kind: Tok.getKind());
4544 break;
4545 }
4546 isInvalid = DS.SetOverflowBehavior(
4547 Kind: OverflowBehaviorType::OverflowBehaviorKind::Wrap, Loc, PrevSpec,
4548 DiagID);
4549 break;
4550 case tok::kw___ob_trap:
4551 if (!getLangOpts().OverflowBehaviorTypes) {
4552 Diag(Loc, DiagID: diag::warn_overflow_behavior_keyword_disabled)
4553 << tok::getKeywordSpelling(Kind: Tok.getKind());
4554 break;
4555 }
4556 isInvalid = DS.SetOverflowBehavior(
4557 Kind: OverflowBehaviorType::OverflowBehaviorKind::Trap, Loc, PrevSpec,
4558 DiagID);
4559 break;
4560
4561 // C++ typename-specifier:
4562 case tok::kw_typename:
4563 if (TryAnnotateTypeOrScopeToken()) {
4564 DS.SetTypeSpecError();
4565 goto DoneWithDeclSpec;
4566 }
4567 if (!Tok.is(K: 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(K: tok::l_paren)) {
4621 ParseAtomicSpecifier(DS);
4622 continue;
4623 }
4624 isInvalid = DS.SetTypeQual(T: DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4625 Lang: 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(Attrs&: 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(Attrs&: 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(rAngleLoc&: EndLoc);
4684 if (Type.isUsable()) {
4685 if (DS.SetTypeSpecType(T: DeclSpec::TST_typename, TagKwLoc: StartLoc, TagNameLoc: StartLoc,
4686 PrevSpec, DiagID, Rep: Type.get(),
4687 Policy: Actions.getASTContext().getPrintingPolicy()))
4688 Diag(Loc: 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
4711 << FixItHint::CreateRemoval(
4712 RemoveRange: 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.
4722 ConsumeAnyToken();
4723
4724 AttrsLastTime = false;
4725 }
4726}
4727
4728static void DiagnoseCountAttributedTypeInUnnamedAnon(ParsingDeclSpec &DS,
4729 Parser &P) {
4730
4731 if (DS.getTypeSpecType() != DeclSpec::TST_struct)
4732 return;
4733
4734 auto *RD = dyn_cast<RecordDecl>(Val: 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>(Val: 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(D: DD.getDecl())) {
4750 P.Diag(Loc: VD->getBeginLoc(), DiagID: diag::err_count_attr_param_not_in_same_struct)
4751 << DD.getDecl() << CAT->getKind() << CAT->isArrayType();
4752 P.Diag(Loc: DD.getDecl()->getBeginLoc(),
4753 DiagID: 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(K: 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(K: 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 S: getCurScope(), AS: AS_none, DS, DeclAttrs: ParsedAttributesView::none(), AnonRecord);
4790 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4791 DS.complete(D: 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(D&: DeclaratorInfo.D);
4808 DiagnoseAndSkipCXX11Attributes();
4809 }
4810
4811 /// struct-declarator: declarator
4812 /// struct-declarator: declarator[opt] ':' constant-expression
4813 if (Tok.isNot(K: tok::colon)) {
4814 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4815 ColonProtectionRAIIObject X(*this);
4816 ParseDeclarator(D&: DeclaratorInfo.D);
4817 } else
4818 DeclaratorInfo.D.SetIdentifier(Id: nullptr, IdLoc: 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.
4823 DiagnoseCountAttributedTypeInUnnamedAnon(DS, P&: *this);
4824
4825 if (TryConsumeToken(Expected: tok::colon)) {
4826 ExprResult Res(ParseConstantExpression());
4827 if (Res.isInvalid())
4828 SkipUntil(T: tok::semi, Flags: StopBeforeMatch);
4829 else
4830 DeclaratorInfo.BitfieldSize = Res.get();
4831 }
4832
4833 // If attributes exist after the declarator, parse them.
4834 MaybeParseGNUAttributes(D&: DeclaratorInfo.D, LateAttrs: LateFieldAttrs);
4835
4836 // We're done with this declarator; invoke the callback.
4837 Decl *Field = FieldsCallback(DeclaratorInfo);
4838 if (Field)
4839 DistributeCLateParsedAttrs(Dcl: Field, LateAttrs: 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(Expected: tok::comma, Loc&: CommaLoc))
4844 return;
4845
4846 FirstDeclarator = false;
4847 }
4848}
4849
4850ParsedAttributes Parser::ParseLexedCAttributeTokens(LateParsedAttribute &LA) {
4851 // Create a fake EOF so that attribute parsing won't go off the end of the
4852 // attribute.
4853 Token AttrEnd;
4854 AttrEnd.startToken();
4855 AttrEnd.setKind(tok::eof);
4856 AttrEnd.setLocation(Tok.getLocation());
4857 AttrEnd.setEofData(LA.Toks.data());
4858 LA.Toks.push_back(Elt: AttrEnd);
4859
4860 // Append the current token at the end of the new token stream so that it
4861 // doesn't get lost.
4862 LA.Toks.push_back(Elt: Tok);
4863 PP.EnterTokenStream(Toks: LA.Toks, /*DisableMacroExpansion=*/true,
4864 /*IsReinject=*/true);
4865 // Drop the current token and bring the first cached one. It's the same token
4866 // as when we entered this function.
4867 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
4868
4869 ParsedAttributes Attrs(AttrFactory);
4870
4871 assert(LA.Decls.size() <= 1 &&
4872 "late field attribute expects to have at most one declaration.");
4873
4874 // Dispatch based on the attribute and parse it
4875 ParseGNUAttributeArgs(AttrName: &LA.AttrName, AttrNameLoc: LA.AttrNameLoc, Attrs, EndLoc: nullptr, ScopeName: nullptr,
4876 ScopeLoc: SourceLocation(), Form: ParsedAttr::Form::GNU(), D: nullptr);
4877
4878 // Due to a parsing error, we either went over the cached tokens or
4879 // there are still cached tokens left, so we skip the leftover tokens.
4880 while (Tok.isNot(K: tok::eof))
4881 ConsumeAnyToken();
4882
4883 // Consume the fake EOF token if it's there
4884 if (Tok.is(K: tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
4885 ConsumeAnyToken();
4886
4887 return Attrs;
4888}
4889
4890void Parser::ParseLexedTypeAttribute(LateParsedTypeAttribute &LA,
4891 ParsedAttributes &OutAttrs) {
4892 ParsedAttributes Attrs = ParseLexedCAttributeTokens(LA);
4893 OutAttrs.takeAllAppendingFrom(Other&: Attrs);
4894}
4895
4896void LateParsedTypeAttribute::ParseInto(ParsedAttributes &OutAttrs) {
4897 // Delegate to the Parser that created this attribute
4898 Self->ParseLexedTypeAttribute(LA&: *this, OutAttrs);
4899}
4900
4901void Parser::TakeTypeAttrsAppendingFrom(LateParsedAttrList &To,
4902 LateParsedAttrList &From) {
4903 LateParsedAttrList::iterator It =
4904 llvm::remove_if(Range&: From, P: [&](LateParsedAttribute *LA) {
4905 if (isa<LateParsedTypeAttribute>(Val: LA)) {
4906 To.push_back(Elt: LA);
4907 return true;
4908 }
4909 return false;
4910 });
4911 From.erase(CS: It, CE: From.end());
4912}
4913
4914void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4915 DeclSpec::TST TagType, RecordDecl *TagDecl) {
4916 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4917 "parsing struct/union body");
4918 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4919
4920 BalancedDelimiterTracker T(*this, tok::l_brace);
4921 if (T.consumeOpen())
4922 return;
4923
4924 ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4925 Actions.ActOnTagStartDefinition(S: getCurScope(), TagDecl);
4926
4927 // `LateAttrParseExperimentalExtOnly=true` requests that only attributes
4928 // marked with `LateAttrParseExperimentalExt` are late parsed.
4929 LateParsedAttrList LateFieldAttrs(/*PSoon=*/true,
4930 /*LateAttrParseExperimentalExtOnly=*/true);
4931
4932 // While we still have something to read, read the declarations in the struct.
4933 while (!tryParseMisplacedModuleImport() && Tok.isNot(K: tok::r_brace) &&
4934 Tok.isNot(K: tok::eof)) {
4935 // Each iteration of this loop reads one struct-declaration.
4936
4937 // Check for extraneous top-level semicolon.
4938 if (Tok.is(K: tok::semi)) {
4939 ConsumeExtraSemi(Kind: ExtraSemiKind::InsideStruct, T: TagType);
4940 continue;
4941 }
4942
4943 // Parse _Static_assert declaration.
4944 if (Tok.isOneOf(Ks: tok::kw__Static_assert, Ks: tok::kw_static_assert)) {
4945 SourceLocation DeclEnd;
4946 ParseStaticAssertDeclaration(DeclEnd);
4947 continue;
4948 }
4949
4950 if (Tok.is(K: tok::annot_pragma_pack)) {
4951 HandlePragmaPack();
4952 continue;
4953 }
4954
4955 if (Tok.is(K: tok::annot_pragma_align)) {
4956 HandlePragmaAlign();
4957 continue;
4958 }
4959
4960 if (Tok.isOneOf(Ks: tok::annot_pragma_openmp, Ks: tok::annot_attr_openmp)) {
4961 // Result can be ignored, because it must be always empty.
4962 AccessSpecifier AS = AS_none;
4963 ParsedAttributes Attrs(AttrFactory);
4964 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4965 continue;
4966 }
4967
4968 if (Tok.is(K: tok::annot_pragma_openacc)) {
4969 AccessSpecifier AS = AS_none;
4970 ParsedAttributes Attrs(AttrFactory);
4971 ParseOpenACCDirectiveDecl(AS, Attrs, TagType, TagDecl);
4972 continue;
4973 }
4974
4975 if (tok::isPragmaAnnotation(K: Tok.getKind())) {
4976 Diag(Loc: Tok.getLocation(), DiagID: diag::err_pragma_misplaced_in_decl)
4977 << DeclSpec::getSpecifierName(
4978 T: TagType, Policy: Actions.getASTContext().getPrintingPolicy());
4979 ConsumeAnnotationToken();
4980 continue;
4981 }
4982
4983 if (!Tok.is(K: tok::at)) {
4984 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) -> Decl * {
4985 // Install the declarator into the current TagDecl.
4986 Decl *Field =
4987 Actions.ActOnField(S: getCurScope(), TagD: TagDecl,
4988 DeclStart: FD.D.getDeclSpec().getSourceRange().getBegin(),
4989 D&: FD.D, BitfieldWidth: FD.BitfieldSize);
4990 FD.complete(D: Field);
4991 return Field;
4992 };
4993
4994 // Parse all the comma separated declarators.
4995 ParsingDeclSpec DS(*this);
4996 ParseStructDeclaration(DS, FieldsCallback: CFieldCallback, LateFieldAttrs: &LateFieldAttrs);
4997 } else { // Handle @defs
4998 ConsumeToken();
4999 if (!Tok.isObjCAtKeyword(objcKey: tok::objc_defs)) {
5000 Diag(Tok, DiagID: diag::err_unexpected_at);
5001 SkipUntil(T: tok::semi);
5002 continue;
5003 }
5004 ConsumeToken();
5005 ExpectAndConsume(ExpectedTok: tok::l_paren);
5006 if (!Tok.is(K: tok::identifier)) {
5007 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
5008 SkipUntil(T: tok::semi);
5009 continue;
5010 }
5011 SmallVector<Decl *, 16> Fields;
5012 Actions.ObjC().ActOnDefs(S: getCurScope(), TagD: TagDecl, DeclStart: Tok.getLocation(),
5013 ClassName: Tok.getIdentifierInfo(), Decls&: Fields);
5014 ConsumeToken();
5015 ExpectAndConsume(ExpectedTok: tok::r_paren);
5016 }
5017
5018 if (TryConsumeToken(Expected: tok::semi))
5019 continue;
5020
5021 if (Tok.is(K: tok::r_brace)) {
5022 ExpectAndConsume(ExpectedTok: tok::semi, Diag: diag::ext_expected_semi_decl_list);
5023 break;
5024 }
5025
5026 ExpectAndConsume(ExpectedTok: tok::semi, Diag: diag::err_expected_semi_decl_list);
5027 // Skip to end of block or statement to avoid ext-warning on extra ';'.
5028 SkipUntil(T: tok::r_brace, Flags: StopAtSemi | StopBeforeMatch);
5029 // If we stopped at a ';', eat it.
5030 TryConsumeToken(Expected: tok::semi);
5031 }
5032
5033 T.consumeClose();
5034
5035 ParsedAttributes attrs(AttrFactory);
5036 // If attributes exist after struct contents, parse them.
5037 MaybeParseGNUAttributes(Attrs&: attrs, LateAttrs: &LateFieldAttrs);
5038
5039 SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
5040
5041 Actions.ActOnFields(S: getCurScope(), RecLoc: RecordLoc, TagDecl, Fields: FieldDecls,
5042 LBrac: T.getOpenLocation(), RBrac: T.getCloseLocation(), AttrList: attrs);
5043
5044 // Late parse field attributes if necessary.
5045 ParseLexedAttributeList(LAs&: LateFieldAttrs, /*D=*/nullptr, /*EnterScope=*/false,
5046 /*OnDefinition=*/false);
5047 StructScope.Exit();
5048 Actions.ActOnTagFinishDefinition(S: getCurScope(), TagDecl, BraceRange: T.getRange());
5049}
5050
5051void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
5052 const ParsedTemplateInfo &TemplateInfo,
5053 AccessSpecifier AS, DeclSpecContext DSC) {
5054 // Parse the tag portion of this.
5055 if (Tok.is(K: tok::code_completion)) {
5056 // Code completion for an enum name.
5057 cutOffParsing();
5058 Actions.CodeCompletion().CodeCompleteTag(S: getCurScope(), TagSpec: DeclSpec::TST_enum);
5059 DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
5060 return;
5061 }
5062
5063 // If attributes exist after tag, parse them.
5064 ParsedAttributes attrs(AttrFactory);
5065 MaybeParseAttributes(WhichAttrKinds: PAKM_GNU | PAKM_Declspec | PAKM_CXX11, Attrs&: attrs);
5066
5067 SourceLocation ScopedEnumKWLoc;
5068 bool IsScopedUsingClassTag = false;
5069
5070 // In C++11, recognize 'enum class' and 'enum struct'.
5071 if (Tok.isOneOf(Ks: tok::kw_class, Ks: tok::kw_struct) && getLangOpts().CPlusPlus) {
5072 Diag(Tok, DiagID: getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
5073 : diag::ext_scoped_enum);
5074 IsScopedUsingClassTag = Tok.is(K: tok::kw_class);
5075 ScopedEnumKWLoc = ConsumeToken();
5076
5077 // Attributes are not allowed between these keywords. Diagnose,
5078 // but then just treat them like they appeared in the right place.
5079 ProhibitAttributes(Attrs&: attrs);
5080
5081 // They are allowed afterwards, though.
5082 MaybeParseAttributes(WhichAttrKinds: PAKM_GNU | PAKM_Declspec | PAKM_CXX11, Attrs&: attrs);
5083 }
5084
5085 // C++11 [temp.explicit]p12:
5086 // The usual access controls do not apply to names used to specify
5087 // explicit instantiations.
5088 // We extend this to also cover explicit specializations. Note that
5089 // we don't suppress if this turns out to be an elaborated type
5090 // specifier.
5091 bool shouldDelayDiagsInTag =
5092 (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation ||
5093 TemplateInfo.Kind == ParsedTemplateKind::ExplicitSpecialization);
5094 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
5095
5096 // Determine whether this declaration is permitted to have an enum-base.
5097 AllowDefiningTypeSpec AllowEnumSpecifier =
5098 isDefiningTypeSpecifierContext(DSC, IsCPlusPlus: getLangOpts().CPlusPlus);
5099 bool CanBeOpaqueEnumDeclaration =
5100 DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
5101 bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
5102 getLangOpts().MicrosoftExt) &&
5103 (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
5104 CanBeOpaqueEnumDeclaration);
5105
5106 // We use a temporary scope when parsing the name specifier for a
5107 // declaration with additional invalid type specifiers.
5108 CXXScopeSpec InvalidDeclScope;
5109 CXXScopeSpec &SS =
5110 DS.hasTypeSpecifier() ? InvalidDeclScope : DS.getTypeSpecScope();
5111 if (getLangOpts().CPlusPlus) {
5112 // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
5113 ColonProtectionRAIIObject X(*this);
5114
5115 CXXScopeSpec Spec;
5116 if (ParseOptionalCXXScopeSpecifier(SS&: Spec, /*ObjectType=*/nullptr,
5117 /*ObjectHasErrors=*/false,
5118 /*EnteringContext=*/true))
5119 return;
5120
5121 if (Spec.isSet() && Tok.isNot(K: tok::identifier)) {
5122 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
5123 DS.SetTypeSpecError();
5124 if (Tok.isNot(K: tok::l_brace)) {
5125 // Has no name and is not a definition.
5126 // Skip the rest of this declarator, up until the comma or semicolon.
5127 SkipUntil(T: tok::comma, Flags: StopAtSemi);
5128 return;
5129 }
5130 }
5131
5132 SS = std::move(Spec);
5133 }
5134
5135 // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
5136 if (Tok.isNot(K: tok::identifier) && Tok.isNot(K: tok::l_brace) &&
5137 Tok.isNot(K: tok::colon)) {
5138 Diag(Tok, DiagID: diag::err_expected_either) << tok::identifier << tok::l_brace;
5139
5140 DS.SetTypeSpecError();
5141 // Skip the rest of this declarator, up until the comma or semicolon.
5142 SkipUntil(T: tok::comma, Flags: StopAtSemi);
5143 return;
5144 }
5145
5146 // If an identifier is present, consume and remember it.
5147 IdentifierInfo *Name = nullptr;
5148 SourceLocation NameLoc;
5149 if (Tok.is(K: tok::identifier)) {
5150 Name = Tok.getIdentifierInfo();
5151 NameLoc = ConsumeToken();
5152 }
5153
5154 if (!Name && ScopedEnumKWLoc.isValid()) {
5155 // C++0x 7.2p2: The optional identifier shall not be omitted in the
5156 // declaration of a scoped enumeration.
5157 Diag(Tok, DiagID: diag::err_scoped_enum_missing_identifier);
5158 ScopedEnumKWLoc = SourceLocation();
5159 IsScopedUsingClassTag = false;
5160 }
5161
5162 // Okay, end the suppression area. We'll decide whether to emit the
5163 // diagnostics in a second.
5164 if (shouldDelayDiagsInTag)
5165 diagsFromTag.done();
5166
5167 TypeResult BaseType;
5168 SourceRange BaseRange;
5169
5170 bool CanBeBitfield =
5171 getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
5172
5173 // Parse the fixed underlying type.
5174 if (Tok.is(K: tok::colon)) {
5175 // This might be an enum-base or part of some unrelated enclosing context.
5176 //
5177 // 'enum E : base' is permitted in two circumstances:
5178 //
5179 // 1) As a defining-type-specifier, when followed by '{'.
5180 // 2) As the sole constituent of a complete declaration -- when DS is empty
5181 // and the next token is ';'.
5182 //
5183 // The restriction to defining-type-specifiers is important to allow parsing
5184 // a ? new enum E : int{}
5185 // _Generic(a, enum E : int{})
5186 // properly.
5187 //
5188 // One additional consideration applies:
5189 //
5190 // C++ [dcl.enum]p1:
5191 // A ':' following "enum nested-name-specifier[opt] identifier" within
5192 // the decl-specifier-seq of a member-declaration is parsed as part of
5193 // an enum-base.
5194 //
5195 // Other language modes supporting enumerations with fixed underlying types
5196 // do not have clear rules on this, so we disambiguate to determine whether
5197 // the tokens form a bit-field width or an enum-base.
5198
5199 if (CanBeBitfield && !isEnumBase(AllowSemi: CanBeOpaqueEnumDeclaration)) {
5200 // Outside C++11, do not interpret the tokens as an enum-base if they do
5201 // not make sense as one. In C++11, it's an error if this happens.
5202 if (getLangOpts().CPlusPlus11)
5203 Diag(Loc: Tok.getLocation(), DiagID: diag::err_anonymous_enum_bitfield);
5204 } else if (CanHaveEnumBase || !ColonIsSacred) {
5205 SourceLocation ColonLoc = ConsumeToken();
5206
5207 // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
5208 // because under -fms-extensions,
5209 // enum E : int *p;
5210 // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
5211 DeclSpec DS(AttrFactory);
5212 // enum-base is not assumed to be a type and therefore requires the
5213 // typename keyword [p0634r3].
5214 ParseSpecifierQualifierList(DS, AllowImplicitTypename: ImplicitTypenameContext::No, AS,
5215 DSC: DeclSpecContext::DSC_type_specifier);
5216 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
5217 DeclaratorContext::TypeName);
5218 BaseType = Actions.ActOnTypeName(D&: DeclaratorInfo);
5219
5220 BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
5221
5222 if (!getLangOpts().ObjC) {
5223 if (getLangOpts().CPlusPlus)
5224 DiagCompat(Loc: ColonLoc, CompatDiagId: diag_compat::enum_fixed_underlying_type)
5225 << BaseRange;
5226 else if (getLangOpts().MicrosoftExt && !getLangOpts().C23)
5227 Diag(Loc: ColonLoc, DiagID: diag::ext_ms_c_enum_fixed_underlying_type)
5228 << BaseRange;
5229 else
5230 Diag(Loc: ColonLoc, DiagID: getLangOpts().C23
5231 ? diag::warn_c17_compat_enum_fixed_underlying_type
5232 : diag::ext_c23_enum_fixed_underlying_type)
5233 << BaseRange;
5234 }
5235 }
5236 }
5237
5238 // There are four options here. If we have 'friend enum foo;' then this is a
5239 // friend declaration, and cannot have an accompanying definition. If we have
5240 // 'enum foo;', then this is a forward declaration. If we have
5241 // 'enum foo {...' then this is a definition. Otherwise we have something
5242 // like 'enum foo xyz', a reference.
5243 //
5244 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
5245 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
5246 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
5247 //
5248 TagUseKind TUK;
5249 if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
5250 TUK = TagUseKind::Reference;
5251 else if (Tok.is(K: tok::l_brace)) {
5252 if (DS.isFriendSpecified()) {
5253 Diag(Loc: Tok.getLocation(), DiagID: diag::err_friend_decl_defines_type)
5254 << SourceRange(DS.getFriendSpecLoc());
5255 ConsumeBrace();
5256 SkipUntil(T: tok::r_brace, Flags: StopAtSemi);
5257 // Discard any other definition-only pieces.
5258 attrs.clear();
5259 ScopedEnumKWLoc = SourceLocation();
5260 IsScopedUsingClassTag = false;
5261 BaseType = TypeResult();
5262 TUK = TagUseKind::Friend;
5263 } else {
5264 TUK = TagUseKind::Definition;
5265 }
5266 } else if (!isTypeSpecifier(DSC) &&
5267 (Tok.is(K: tok::semi) ||
5268 (Tok.isAtStartOfLine() &&
5269 !isValidAfterTypeSpecifier(CouldBeBitfield: CanBeBitfield)))) {
5270 // An opaque-enum-declaration is required to be standalone (no preceding or
5271 // following tokens in the declaration). Sema enforces this separately by
5272 // diagnosing anything else in the DeclSpec.
5273 TUK = DS.isFriendSpecified() ? TagUseKind::Friend : TagUseKind::Declaration;
5274 if (Tok.isNot(K: tok::semi)) {
5275 // A semicolon was missing after this declaration. Diagnose and recover.
5276 ExpectAndConsume(ExpectedTok: tok::semi, Diag: diag::err_expected_after, DiagMsg: "enum");
5277 PP.EnterToken(Tok, /*IsReinject=*/true);
5278 Tok.setKind(tok::semi);
5279 }
5280 } else {
5281 TUK = TagUseKind::Reference;
5282 }
5283
5284 bool IsElaboratedTypeSpecifier =
5285 TUK == TagUseKind::Reference || TUK == TagUseKind::Friend;
5286
5287 // If this is an elaborated type specifier nested in a larger declaration,
5288 // and we delayed diagnostics before, just merge them into the current pool.
5289 if (TUK == TagUseKind::Reference && shouldDelayDiagsInTag) {
5290 diagsFromTag.redelay();
5291 }
5292
5293 MultiTemplateParamsArg TParams;
5294 if (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate &&
5295 TUK != TagUseKind::Reference) {
5296 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
5297 // Skip the rest of this declarator, up until the comma or semicolon.
5298 Diag(Tok, DiagID: diag::err_enum_template);
5299 SkipUntil(T: tok::comma, Flags: StopAtSemi);
5300 return;
5301 }
5302
5303 if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation) {
5304 // Enumerations can't be explicitly instantiated.
5305 DS.SetTypeSpecError();
5306 Diag(Loc: StartLoc, DiagID: diag::err_explicit_instantiation_enum);
5307 return;
5308 }
5309
5310 assert(TemplateInfo.TemplateParams && "no template parameters");
5311 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
5312 TemplateInfo.TemplateParams->size());
5313 SS.setTemplateParamLists(TParams);
5314 }
5315
5316 if (!Name && TUK != TagUseKind::Definition) {
5317 Diag(Tok, DiagID: diag::err_enumerator_unnamed_no_def);
5318
5319 DS.SetTypeSpecError();
5320 // Skip the rest of this declarator, up until the comma or semicolon.
5321 SkipUntil(T: tok::comma, Flags: StopAtSemi);
5322 return;
5323 }
5324
5325 // An elaborated-type-specifier has a much more constrained grammar:
5326 //
5327 // 'enum' nested-name-specifier[opt] identifier
5328 //
5329 // If we parsed any other bits, reject them now.
5330 //
5331 // MSVC and (for now at least) Objective-C permit a full enum-specifier
5332 // or opaque-enum-declaration anywhere.
5333 if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
5334 !getLangOpts().ObjC) {
5335 ProhibitCXX11Attributes(Attrs&: attrs, AttrDiagID: diag::err_attributes_not_allowed,
5336 KeywordDiagID: diag::err_keyword_not_allowed,
5337 /*DiagnoseEmptyAttrs=*/true);
5338 if (BaseType.isUsable())
5339 Diag(Loc: BaseRange.getBegin(), DiagID: diag::ext_enum_base_in_type_specifier)
5340 << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
5341 else if (ScopedEnumKWLoc.isValid())
5342 Diag(Loc: ScopedEnumKWLoc, DiagID: diag::ext_elaborated_enum_class)
5343 << FixItHint::CreateRemoval(RemoveRange: ScopedEnumKWLoc) << IsScopedUsingClassTag;
5344 }
5345
5346 stripTypeAttributesOffDeclSpec(Attrs&: attrs, DS, TUK);
5347
5348 SkipBodyInfo SkipBody;
5349 if (!Name && TUK == TagUseKind::Definition && Tok.is(K: tok::l_brace) &&
5350 NextToken().is(K: tok::identifier))
5351 SkipBody = Actions.shouldSkipAnonEnumBody(S: getCurScope(),
5352 II: NextToken().getIdentifierInfo(),
5353 IILoc: NextToken().getLocation());
5354
5355 bool Owned = false;
5356 bool IsDependent = false;
5357 const char *PrevSpec = nullptr;
5358 unsigned DiagID;
5359 Decl *TagDecl =
5360 Actions.ActOnTag(S: getCurScope(), TagSpec: DeclSpec::TST_enum, TUK, KWLoc: StartLoc, SS,
5361 Name, NameLoc, Attr: attrs, AS, ModulePrivateLoc: DS.getModulePrivateSpecLoc(),
5362 TemplateParameterLists: TParams, OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc,
5363 ScopedEnumUsesClassTag: IsScopedUsingClassTag,
5364 UnderlyingType: BaseType, IsTypeSpecifier: DSC == DeclSpecContext::DSC_type_specifier,
5365 IsTemplateParamOrArg: DSC == DeclSpecContext::DSC_template_param ||
5366 DSC == DeclSpecContext::DSC_template_type_arg,
5367 OOK: OffsetOfState, SkipBody: &SkipBody).get();
5368
5369 if (SkipBody.ShouldSkip) {
5370 assert(TUK == TagUseKind::Definition && "can only skip a definition");
5371
5372 BalancedDelimiterTracker T(*this, tok::l_brace);
5373 T.consumeOpen();
5374 T.skipToEnd();
5375
5376 if (DS.SetTypeSpecType(T: DeclSpec::TST_enum, TagKwLoc: StartLoc,
5377 TagNameLoc: NameLoc.isValid() ? NameLoc : StartLoc,
5378 PrevSpec, DiagID, Rep: TagDecl, Owned,
5379 Policy: Actions.getASTContext().getPrintingPolicy()))
5380 Diag(Loc: StartLoc, DiagID) << PrevSpec;
5381 return;
5382 }
5383
5384 if (IsDependent) {
5385 // This enum has a dependent nested-name-specifier. Handle it as a
5386 // dependent tag.
5387 if (!Name) {
5388 DS.SetTypeSpecError();
5389 Diag(Tok, DiagID: diag::err_expected_type_name_after_typename);
5390 return;
5391 }
5392
5393 TypeResult Type = Actions.ActOnDependentTag(
5394 S: getCurScope(), TagSpec: DeclSpec::TST_enum, TUK, SS, Name, TagLoc: StartLoc, NameLoc);
5395 if (Type.isInvalid()) {
5396 DS.SetTypeSpecError();
5397 return;
5398 }
5399
5400 if (DS.SetTypeSpecType(T: DeclSpec::TST_typename, TagKwLoc: StartLoc,
5401 TagNameLoc: NameLoc.isValid() ? NameLoc : StartLoc,
5402 PrevSpec, DiagID, Rep: Type.get(),
5403 Policy: Actions.getASTContext().getPrintingPolicy()))
5404 Diag(Loc: StartLoc, DiagID) << PrevSpec;
5405
5406 return;
5407 }
5408
5409 if (!TagDecl) {
5410 // The action failed to produce an enumeration tag. If this is a
5411 // definition, consume the entire definition.
5412 if (Tok.is(K: tok::l_brace) && TUK != TagUseKind::Reference) {
5413 ConsumeBrace();
5414 SkipUntil(T: tok::r_brace, Flags: StopAtSemi);
5415 }
5416
5417 DS.SetTypeSpecError();
5418 return;
5419 }
5420
5421 if (Tok.is(K: tok::l_brace) && TUK == TagUseKind::Definition) {
5422 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
5423 ParseEnumBody(StartLoc, TagDecl: D, SkipBody: &SkipBody);
5424 if (SkipBody.CheckSameAsPrevious &&
5425 !Actions.ActOnDuplicateDefinition(S: getCurScope(), Prev: TagDecl, SkipBody)) {
5426 DS.SetTypeSpecError();
5427 return;
5428 }
5429 }
5430
5431 if (DS.SetTypeSpecType(T: DeclSpec::TST_enum, TagKwLoc: StartLoc,
5432 TagNameLoc: NameLoc.isValid() ? NameLoc : StartLoc,
5433 PrevSpec, DiagID, Rep: TagDecl, Owned,
5434 Policy: Actions.getASTContext().getPrintingPolicy()))
5435 Diag(Loc: StartLoc, DiagID) << PrevSpec;
5436}
5437
5438void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl,
5439 SkipBodyInfo *SkipBody) {
5440 // Enter the scope of the enum body and start the definition.
5441 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
5442 Actions.ActOnTagStartDefinition(S: getCurScope(), TagDecl: EnumDecl);
5443
5444 BalancedDelimiterTracker T(*this, tok::l_brace);
5445 T.consumeOpen();
5446
5447 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
5448 if (Tok.is(K: tok::r_brace) && !getLangOpts().CPlusPlus) {
5449 if (getLangOpts().MicrosoftExt)
5450 Diag(Loc: T.getOpenLocation(), DiagID: diag::ext_ms_c_empty_enum_type)
5451 << SourceRange(T.getOpenLocation(), Tok.getLocation());
5452 else
5453 Diag(Tok, DiagID: diag::err_empty_enum);
5454 }
5455
5456 SmallVector<Decl *, 32> EnumConstantDecls;
5457 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
5458
5459 Decl *LastEnumConstDecl = nullptr;
5460
5461 // Parse the enumerator-list.
5462 while (Tok.isNot(K: tok::r_brace)) {
5463 // Parse enumerator. If failed, try skipping till the start of the next
5464 // enumerator definition.
5465 if (Tok.isNot(K: tok::identifier)) {
5466 Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected) << tok::identifier;
5467 if (SkipUntil(T1: tok::comma, T2: tok::r_brace, Flags: StopBeforeMatch) &&
5468 TryConsumeToken(Expected: tok::comma))
5469 continue;
5470 break;
5471 }
5472 IdentifierInfo *Ident = Tok.getIdentifierInfo();
5473 SourceLocation IdentLoc = ConsumeToken();
5474
5475 // If attributes exist after the enumerator, parse them.
5476 ParsedAttributes attrs(AttrFactory);
5477 MaybeParseGNUAttributes(Attrs&: attrs);
5478 if (isAllowedCXX11AttributeSpecifier()) {
5479 if (getLangOpts().CPlusPlus)
5480 Diag(Loc: Tok.getLocation(), DiagID: getLangOpts().CPlusPlus17
5481 ? diag::warn_cxx14_compat_ns_enum_attribute
5482 : diag::ext_ns_enum_attribute)
5483 << 1 /*enumerator*/;
5484 ParseCXX11Attributes(attrs);
5485 }
5486
5487 SourceLocation EqualLoc;
5488 ExprResult AssignedVal;
5489 EnumAvailabilityDiags.emplace_back(Args&: *this);
5490
5491 EnterExpressionEvaluationContext ConstantEvaluated(
5492 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5493 if (TryConsumeToken(Expected: tok::equal, Loc&: EqualLoc)) {
5494 AssignedVal = ParseConstantExpressionInExprEvalContext();
5495 if (AssignedVal.isInvalid())
5496 SkipUntil(T1: tok::comma, T2: tok::r_brace, Flags: StopBeforeMatch);
5497 }
5498
5499 // Install the enumerator constant into EnumDecl.
5500 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
5501 S: getCurScope(), EnumDecl, LastEnumConstant: LastEnumConstDecl, IdLoc: IdentLoc, Id: Ident, Attrs: attrs,
5502 EqualLoc, Val: AssignedVal.get(), SkipBody);
5503 EnumAvailabilityDiags.back().done();
5504
5505 EnumConstantDecls.push_back(Elt: EnumConstDecl);
5506 LastEnumConstDecl = EnumConstDecl;
5507
5508 if (Tok.is(K: tok::identifier)) {
5509 // We're missing a comma between enumerators.
5510 SourceLocation Loc = getEndOfPreviousToken();
5511 Diag(Loc, DiagID: diag::err_enumerator_list_missing_comma)
5512 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: ", ");
5513 continue;
5514 }
5515
5516 // Emumerator definition must be finished, only comma or r_brace are
5517 // allowed here.
5518 SourceLocation CommaLoc;
5519 if (Tok.isNot(K: tok::r_brace) && !TryConsumeToken(Expected: tok::comma, Loc&: CommaLoc)) {
5520 if (EqualLoc.isValid())
5521 Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected_either) << tok::r_brace
5522 << tok::comma;
5523 else
5524 Diag(Loc: Tok.getLocation(), DiagID: diag::err_expected_end_of_enumerator);
5525 if (SkipUntil(T1: tok::comma, T2: tok::r_brace, Flags: StopBeforeMatch)) {
5526 if (TryConsumeToken(Expected: tok::comma, Loc&: CommaLoc))
5527 continue;
5528 } else {
5529 break;
5530 }
5531 }
5532
5533 // If comma is followed by r_brace, emit appropriate warning.
5534 if (Tok.is(K: tok::r_brace) && CommaLoc.isValid()) {
5535 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
5536 Diag(Loc: CommaLoc, DiagID: getLangOpts().CPlusPlus ?
5537 diag::ext_enumerator_list_comma_cxx :
5538 diag::ext_enumerator_list_comma_c)
5539 << FixItHint::CreateRemoval(RemoveRange: CommaLoc);
5540 else if (getLangOpts().CPlusPlus11)
5541 Diag(Loc: CommaLoc, DiagID: diag::warn_cxx98_compat_enumerator_list_comma)
5542 << FixItHint::CreateRemoval(RemoveRange: CommaLoc);
5543 break;
5544 }
5545 }
5546
5547 // Eat the }.
5548 T.consumeClose();
5549
5550 // If attributes exist after the identifier list, parse them.
5551 ParsedAttributes attrs(AttrFactory);
5552 MaybeParseGNUAttributes(Attrs&: attrs);
5553
5554 Actions.ActOnEnumBody(EnumLoc: StartLoc, BraceRange: T.getRange(), EnumDecl, Elements: EnumConstantDecls,
5555 S: getCurScope(), Attr: attrs);
5556
5557 // Now handle enum constant availability diagnostics.
5558 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
5559 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
5560 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
5561 EnumAvailabilityDiags[i].redelay();
5562 PD.complete(D: EnumConstantDecls[i]);
5563 }
5564
5565 EnumScope.Exit();
5566 Actions.ActOnTagFinishDefinition(S: getCurScope(), TagDecl: EnumDecl, BraceRange: T.getRange());
5567
5568 // The next token must be valid after an enum definition. If not, a ';'
5569 // was probably forgotten.
5570 bool CanBeBitfield = getCurScope()->isClassScope();
5571 if (!isValidAfterTypeSpecifier(CouldBeBitfield: CanBeBitfield)) {
5572 ExpectAndConsume(ExpectedTok: tok::semi, Diag: diag::err_expected_after, DiagMsg: "enum");
5573 // Push this token back into the preprocessor and change our current token
5574 // to ';' so that the rest of the code recovers as though there were an
5575 // ';' after the definition.
5576 PP.EnterToken(Tok, /*IsReinject=*/true);
5577 Tok.setKind(tok::semi);
5578 }
5579}
5580
5581bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
5582 switch (Tok.getKind()) {
5583 default: return false;
5584 // type-specifiers
5585 case tok::kw_short:
5586 case tok::kw_long:
5587 case tok::kw___int64:
5588 case tok::kw___int128:
5589 case tok::kw_signed:
5590 case tok::kw_unsigned:
5591 case tok::kw__Complex:
5592 case tok::kw__Imaginary:
5593 case tok::kw_void:
5594 case tok::kw_char:
5595 case tok::kw_wchar_t:
5596 case tok::kw_char8_t:
5597 case tok::kw_char16_t:
5598 case tok::kw_char32_t:
5599 case tok::kw_int:
5600 case tok::kw__ExtInt:
5601 case tok::kw__BitInt:
5602 case tok::kw___bf16:
5603 case tok::kw_half:
5604 case tok::kw_float:
5605 case tok::kw_double:
5606 case tok::kw__Accum:
5607 case tok::kw__Fract:
5608 case tok::kw__Float16:
5609 case tok::kw___float128:
5610 case tok::kw___ibm128:
5611 case tok::kw_bool:
5612 case tok::kw__Bool:
5613 case tok::kw__Decimal32:
5614 case tok::kw__Decimal64:
5615 case tok::kw__Decimal128:
5616 case tok::kw___vector:
5617#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5618#include "clang/Basic/OpenCLImageTypes.def"
5619#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
5620#include "clang/Basic/HLSLIntangibleTypes.def"
5621
5622 // struct-or-union-specifier (C99) or class-specifier (C++)
5623 case tok::kw_class:
5624 case tok::kw_struct:
5625 case tok::kw___interface:
5626 case tok::kw_union:
5627 // enum-specifier
5628 case tok::kw_enum:
5629
5630 case tok::kw_typeof:
5631 case tok::kw_typeof_unqual:
5632
5633 // C11 _Atomic
5634 case tok::kw__Atomic:
5635
5636 // typedef-name
5637 case tok::annot_typename:
5638 return true;
5639 }
5640}
5641
5642bool Parser::isTypeSpecifierQualifier(const Token &Tok) {
5643 switch (Tok.getKind()) {
5644 default: return false;
5645
5646 case tok::identifier: // foo::bar
5647 if (TryAltiVecVectorToken())
5648 return true;
5649 [[fallthrough]];
5650 case tok::kw_typename: // typename T::type
5651 // Annotate typenames and C++ scope specifiers. If we get one, just
5652 // recurse to handle whatever we get.
5653 if (TryAnnotateTypeOrScopeToken())
5654 return true;
5655 if (getCurToken().is(K: tok::identifier))
5656 return false;
5657 return isTypeSpecifierQualifier(Tok: getCurToken());
5658
5659 case tok::coloncolon: // ::foo::bar
5660 if (NextToken().is(K: tok::kw_new) || // ::new
5661 NextToken().is(K: tok::kw_delete)) // ::delete
5662 return false;
5663
5664 if (TryAnnotateTypeOrScopeToken())
5665 return true;
5666 return isTypeSpecifierQualifier(Tok: getCurToken());
5667
5668 // GNU attributes support.
5669 case tok::kw___attribute:
5670 // C23/GNU typeof support.
5671 case tok::kw_typeof:
5672 case tok::kw_typeof_unqual:
5673
5674 // type-specifiers
5675 case tok::kw_short:
5676 case tok::kw_long:
5677 case tok::kw___int64:
5678 case tok::kw___int128:
5679 case tok::kw_signed:
5680 case tok::kw_unsigned:
5681 case tok::kw__Complex:
5682 case tok::kw__Imaginary:
5683 case tok::kw_void:
5684 case tok::kw_char:
5685 case tok::kw_wchar_t:
5686 case tok::kw_char8_t:
5687 case tok::kw_char16_t:
5688 case tok::kw_char32_t:
5689 case tok::kw_int:
5690 case tok::kw__ExtInt:
5691 case tok::kw__BitInt:
5692 case tok::kw_half:
5693 case tok::kw___bf16:
5694 case tok::kw_float:
5695 case tok::kw_double:
5696 case tok::kw__Accum:
5697 case tok::kw__Fract:
5698 case tok::kw__Float16:
5699 case tok::kw___float128:
5700 case tok::kw___ibm128:
5701 case tok::kw_bool:
5702 case tok::kw__Bool:
5703 case tok::kw__Decimal32:
5704 case tok::kw__Decimal64:
5705 case tok::kw__Decimal128:
5706 case tok::kw___vector:
5707#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5708#include "clang/Basic/OpenCLImageTypes.def"
5709#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
5710#include "clang/Basic/HLSLIntangibleTypes.def"
5711
5712 // struct-or-union-specifier (C99) or class-specifier (C++)
5713 case tok::kw_class:
5714 case tok::kw_struct:
5715 case tok::kw___interface:
5716 case tok::kw_union:
5717 // enum-specifier
5718 case tok::kw_enum:
5719
5720 // type-qualifier
5721 case tok::kw_const:
5722 case tok::kw_volatile:
5723 case tok::kw_restrict:
5724 case tok::kw___ob_wrap:
5725 case tok::kw___ob_trap:
5726 case tok::kw__Sat:
5727
5728 // Debugger support.
5729 case tok::kw___unknown_anytype:
5730
5731 // typedef-name
5732 case tok::annot_typename:
5733 return true;
5734
5735 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5736 case tok::less:
5737 return getLangOpts().ObjC;
5738
5739 case tok::kw___cdecl:
5740 case tok::kw___stdcall:
5741 case tok::kw___fastcall:
5742 case tok::kw___thiscall:
5743 case tok::kw___regcall:
5744 case tok::kw___vectorcall:
5745 case tok::kw___w64:
5746 case tok::kw___ptr64:
5747 case tok::kw___ptr32:
5748 case tok::kw___pascal:
5749 case tok::kw___unaligned:
5750 case tok::kw___ptrauth:
5751
5752 case tok::kw__Nonnull:
5753 case tok::kw__Nullable:
5754 case tok::kw__Nullable_result:
5755 case tok::kw__Null_unspecified:
5756
5757 case tok::kw___kindof:
5758
5759 case tok::kw___private:
5760 case tok::kw___local:
5761 case tok::kw___global:
5762 case tok::kw___constant:
5763 case tok::kw___generic:
5764 case tok::kw___read_only:
5765 case tok::kw___read_write:
5766 case tok::kw___write_only:
5767 case tok::kw___funcref:
5768 return true;
5769
5770 case tok::kw_private:
5771 return getLangOpts().OpenCL;
5772
5773 // C11 _Atomic
5774 case tok::kw__Atomic:
5775 return true;
5776
5777 // HLSL type qualifiers
5778 case tok::kw_groupshared:
5779 case tok::kw_in:
5780 case tok::kw_inout:
5781 case tok::kw_out:
5782 case tok::kw_row_major:
5783 case tok::kw_column_major:
5784 return getLangOpts().HLSL;
5785 }
5786}
5787
5788Parser::DeclGroupPtrTy Parser::ParseTopLevelStmtDecl() {
5789 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode");
5790
5791 // Parse a top-level-stmt.
5792 Parser::StmtVector Stmts;
5793 ParsedStmtContext SubStmtCtx = ParsedStmtContext();
5794 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
5795 Scope::CompoundStmtScope);
5796 TopLevelStmtDecl *TLSD = Actions.ActOnStartTopLevelStmtDecl(S: getCurScope());
5797 StmtResult R = ParseStatementOrDeclaration(Stmts, StmtCtx: SubStmtCtx);
5798 Actions.ActOnFinishTopLevelStmtDecl(D: TLSD, Statement: R.get());
5799 if (!R.isUsable())
5800 R = Actions.ActOnNullStmt(SemiLoc: Tok.getLocation());
5801
5802 if (Tok.is(K: tok::annot_repl_input_end) &&
5803 Tok.getAnnotationValue() != nullptr) {
5804 ConsumeAnnotationToken();
5805 TLSD->setSemiMissing();
5806 }
5807
5808 SmallVector<Decl *, 2> DeclsInGroup;
5809 DeclsInGroup.push_back(Elt: TLSD);
5810
5811 // Currently happens for things like -fms-extensions and use `__if_exists`.
5812 for (Stmt *S : Stmts) {
5813 // Here we should be safe as `__if_exists` and friends are not introducing
5814 // new variables which need to live outside file scope.
5815 TopLevelStmtDecl *D = Actions.ActOnStartTopLevelStmtDecl(S: getCurScope());
5816 Actions.ActOnFinishTopLevelStmtDecl(D, Statement: S);
5817 DeclsInGroup.push_back(Elt: D);
5818 }
5819
5820 return Actions.BuildDeclaratorGroup(Group: DeclsInGroup);
5821}
5822
5823bool Parser::isDeclarationSpecifier(
5824 ImplicitTypenameContext AllowImplicitTypename,
5825 bool DisambiguatingWithExpression) {
5826 switch (Tok.getKind()) {
5827 default: return false;
5828
5829 // OpenCL 2.0 and later define this keyword.
5830 case tok::kw_pipe:
5831 return getLangOpts().OpenCL &&
5832 getLangOpts().getOpenCLCompatibleVersion() >= 200;
5833
5834 case tok::identifier: // foo::bar
5835 // Unfortunate hack to support "Class.factoryMethod" notation.
5836 if (getLangOpts().ObjC && NextToken().is(K: tok::period))
5837 return false;
5838 if (TryAltiVecVectorToken())
5839 return true;
5840 [[fallthrough]];
5841 case tok::kw_decltype: // decltype(T())::type
5842 case tok::kw_typename: // typename T::type
5843 // Annotate typenames and C++ scope specifiers. If we get one, just
5844 // recurse to handle whatever we get.
5845 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
5846 return true;
5847 if (TryAnnotateTypeConstraint())
5848 return true;
5849 if (Tok.is(K: tok::identifier))
5850 return false;
5851
5852 // If we're in Objective-C and we have an Objective-C class type followed
5853 // by an identifier and then either ':' or ']', in a place where an
5854 // expression is permitted, then this is probably a class message send
5855 // missing the initial '['. In this case, we won't consider this to be
5856 // the start of a declaration.
5857 if (DisambiguatingWithExpression &&
5858 isStartOfObjCClassMessageMissingOpenBracket())
5859 return false;
5860
5861 return isDeclarationSpecifier(AllowImplicitTypename);
5862
5863 case tok::coloncolon: // ::foo::bar
5864 if (!getLangOpts().CPlusPlus)
5865 return false;
5866 if (NextToken().is(K: tok::kw_new) || // ::new
5867 NextToken().is(K: tok::kw_delete)) // ::delete
5868 return false;
5869
5870 // Annotate typenames and C++ scope specifiers. If we get one, just
5871 // recurse to handle whatever we get.
5872 if (TryAnnotateTypeOrScopeToken())
5873 return true;
5874 return isDeclarationSpecifier(AllowImplicitTypename: ImplicitTypenameContext::No);
5875
5876 // storage-class-specifier
5877 case tok::kw_typedef:
5878 case tok::kw_extern:
5879 case tok::kw___private_extern__:
5880 case tok::kw_static:
5881 case tok::kw_auto:
5882 case tok::kw___auto_type:
5883 case tok::kw_register:
5884 case tok::kw___thread:
5885 case tok::kw_thread_local:
5886 case tok::kw__Thread_local:
5887
5888 // Modules
5889 case tok::kw___module_private__:
5890
5891 // Debugger support
5892 case tok::kw___unknown_anytype:
5893
5894 // type-specifiers
5895 case tok::kw_short:
5896 case tok::kw_long:
5897 case tok::kw___int64:
5898 case tok::kw___int128:
5899 case tok::kw_signed:
5900 case tok::kw_unsigned:
5901 case tok::kw__Complex:
5902 case tok::kw__Imaginary:
5903 case tok::kw_void:
5904 case tok::kw_char:
5905 case tok::kw_wchar_t:
5906 case tok::kw_char8_t:
5907 case tok::kw_char16_t:
5908 case tok::kw_char32_t:
5909
5910 case tok::kw_int:
5911 case tok::kw__ExtInt:
5912 case tok::kw__BitInt:
5913 case tok::kw_half:
5914 case tok::kw___bf16:
5915 case tok::kw_float:
5916 case tok::kw_double:
5917 case tok::kw__Accum:
5918 case tok::kw__Fract:
5919 case tok::kw__Float16:
5920 case tok::kw___float128:
5921 case tok::kw___ibm128:
5922 case tok::kw_bool:
5923 case tok::kw__Bool:
5924 case tok::kw__Decimal32:
5925 case tok::kw__Decimal64:
5926 case tok::kw__Decimal128:
5927 case tok::kw___vector:
5928
5929 // struct-or-union-specifier (C99) or class-specifier (C++)
5930 case tok::kw_class:
5931 case tok::kw_struct:
5932 case tok::kw_union:
5933 case tok::kw___interface:
5934 // enum-specifier
5935 case tok::kw_enum:
5936
5937 // type-qualifier
5938 case tok::kw_const:
5939 case tok::kw_volatile:
5940 case tok::kw_restrict:
5941 case tok::kw___ob_wrap:
5942 case tok::kw___ob_trap:
5943 case tok::kw__Sat:
5944
5945 // function-specifier
5946 case tok::kw_inline:
5947 case tok::kw_virtual:
5948 case tok::kw_explicit:
5949 case tok::kw__Noreturn:
5950
5951 // alignment-specifier
5952 case tok::kw__Alignas:
5953
5954 // friend keyword.
5955 case tok::kw_friend:
5956
5957 // static_assert-declaration
5958 case tok::kw_static_assert:
5959 case tok::kw__Static_assert:
5960
5961 // C23/GNU typeof support.
5962 case tok::kw_typeof:
5963 case tok::kw_typeof_unqual:
5964
5965 // GNU attributes.
5966 case tok::kw___attribute:
5967
5968 // C++11 decltype and constexpr.
5969 case tok::annot_decltype:
5970 case tok::annot_pack_indexing_type:
5971 case tok::kw_constexpr:
5972
5973 // C++20 consteval and constinit.
5974 case tok::kw_consteval:
5975 case tok::kw_constinit:
5976
5977 // C11 _Atomic
5978 case tok::kw__Atomic:
5979 return true;
5980
5981 case tok::kw_alignas:
5982 // alignas is a type-specifier-qualifier in C23, which is a kind of
5983 // declaration-specifier. Outside of C23 mode (including in C++), it is not.
5984 return getLangOpts().C23;
5985
5986 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5987 case tok::less:
5988 return getLangOpts().ObjC;
5989
5990 // typedef-name
5991 case tok::annot_typename:
5992 return !DisambiguatingWithExpression ||
5993 !isStartOfObjCClassMessageMissingOpenBracket();
5994
5995 // placeholder-type-specifier
5996 case tok::annot_template_id: {
5997 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Tok);
5998 if (TemplateId->hasInvalidName())
5999 return true;
6000 // FIXME: What about type templates that have only been annotated as
6001 // annot_template_id, not as annot_typename?
6002 return isTypeConstraintAnnotation() &&
6003 (NextToken().is(K: tok::kw_auto) || NextToken().is(K: tok::kw_decltype));
6004 }
6005
6006 case tok::annot_cxxscope: {
6007 TemplateIdAnnotation *TemplateId =
6008 NextToken().is(K: tok::annot_template_id)
6009 ? takeTemplateIdAnnotation(tok: NextToken())
6010 : nullptr;
6011 if (TemplateId && TemplateId->hasInvalidName())
6012 return true;
6013 // FIXME: What about type templates that have only been annotated as
6014 // annot_template_id, not as annot_typename?
6015 if (NextToken().is(K: tok::identifier) && TryAnnotateTypeConstraint())
6016 return true;
6017 return isTypeConstraintAnnotation() &&
6018 GetLookAheadToken(N: 2).isOneOf(Ks: tok::kw_auto, Ks: tok::kw_decltype);
6019 }
6020
6021 case tok::kw___declspec:
6022 case tok::kw___cdecl:
6023 case tok::kw___stdcall:
6024 case tok::kw___fastcall:
6025 case tok::kw___thiscall:
6026 case tok::kw___regcall:
6027 case tok::kw___vectorcall:
6028 case tok::kw___w64:
6029 case tok::kw___sptr:
6030 case tok::kw___uptr:
6031 case tok::kw___ptr64:
6032 case tok::kw___ptr32:
6033 case tok::kw___forceinline:
6034 case tok::kw___pascal:
6035 case tok::kw___unaligned:
6036 case tok::kw___ptrauth:
6037
6038 case tok::kw__Nonnull:
6039 case tok::kw__Nullable:
6040 case tok::kw__Nullable_result:
6041 case tok::kw__Null_unspecified:
6042
6043 case tok::kw___kindof:
6044
6045 case tok::kw___private:
6046 case tok::kw___local:
6047 case tok::kw___global:
6048 case tok::kw___constant:
6049 case tok::kw___generic:
6050 case tok::kw___read_only:
6051 case tok::kw___read_write:
6052 case tok::kw___write_only:
6053#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
6054#include "clang/Basic/OpenCLImageTypes.def"
6055#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
6056#include "clang/Basic/HLSLIntangibleTypes.def"
6057
6058 case tok::kw___funcref:
6059 case tok::kw_groupshared:
6060 return true;
6061
6062 case tok::kw_row_major:
6063 case tok::kw_column_major:
6064 return getLangOpts().HLSL;
6065
6066 case tok::kw_private:
6067 return getLangOpts().OpenCL;
6068 }
6069}
6070
6071bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide,
6072 DeclSpec::FriendSpecified IsFriend,
6073 const ParsedTemplateInfo *TemplateInfo) {
6074 RevertingTentativeParsingAction TPA(*this);
6075 // Parse the C++ scope specifier.
6076 CXXScopeSpec SS;
6077 if (TemplateInfo && TemplateInfo->TemplateParams)
6078 SS.setTemplateParamLists(*TemplateInfo->TemplateParams);
6079
6080 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6081 /*ObjectHasErrors=*/false,
6082 /*EnteringContext=*/true)) {
6083 return false;
6084 }
6085
6086 // Parse the constructor name.
6087 if (Tok.is(K: tok::identifier)) {
6088 // We already know that we have a constructor name; just consume
6089 // the token.
6090 ConsumeToken();
6091 } else if (Tok.is(K: tok::annot_template_id)) {
6092 ConsumeAnnotationToken();
6093 } else {
6094 return false;
6095 }
6096
6097 // There may be attributes here, appertaining to the constructor name or type
6098 // we just stepped past.
6099 SkipCXX11Attributes();
6100
6101 // Current class name must be followed by a left parenthesis.
6102 if (Tok.isNot(K: tok::l_paren)) {
6103 return false;
6104 }
6105 ConsumeParen();
6106
6107 // A right parenthesis, or ellipsis followed by a right parenthesis signals
6108 // that we have a constructor.
6109 if (Tok.is(K: tok::r_paren) ||
6110 (Tok.is(K: tok::ellipsis) && NextToken().is(K: tok::r_paren))) {
6111 return true;
6112 }
6113
6114 // A C++11 attribute here signals that we have a constructor, and is an
6115 // attribute on the first constructor parameter.
6116 if (isCXX11AttributeSpecifier(/*Disambiguate=*/false,
6117 /*OuterMightBeMessageSend=*/true) !=
6118 CXX11AttributeKind::NotAttributeSpecifier) {
6119 return true;
6120 }
6121
6122 // If we need to, enter the specified scope.
6123 DeclaratorScopeObj DeclScopeObj(*this, SS);
6124 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(S: getCurScope(), SS))
6125 DeclScopeObj.EnterDeclaratorScope();
6126
6127 // Optionally skip Microsoft attributes.
6128 ParsedAttributes Attrs(AttrFactory);
6129 MaybeParseMicrosoftAttributes(Attrs);
6130
6131 // Check whether the next token(s) are part of a declaration
6132 // specifier, in which case we have the start of a parameter and,
6133 // therefore, we know that this is a constructor.
6134 // Due to an ambiguity with implicit typename, the above is not enough.
6135 // Additionally, check to see if we are a friend.
6136 // If we parsed a scope specifier as well as friend,
6137 // we might be parsing a friend constructor.
6138 bool IsConstructor = false;
6139 ImplicitTypenameContext ITC = IsFriend && !SS.isSet()
6140 ? ImplicitTypenameContext::No
6141 : ImplicitTypenameContext::Yes;
6142 // Constructors cannot have this parameters, but we support that scenario here
6143 // to improve diagnostic.
6144 if (Tok.is(K: tok::kw_this)) {
6145 ConsumeToken();
6146 return isDeclarationSpecifier(AllowImplicitTypename: ITC);
6147 }
6148
6149 if (isDeclarationSpecifier(AllowImplicitTypename: ITC))
6150 IsConstructor = true;
6151 else if (Tok.is(K: tok::identifier) ||
6152 (Tok.is(K: tok::annot_cxxscope) && NextToken().is(K: tok::identifier))) {
6153 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
6154 // This might be a parenthesized member name, but is more likely to
6155 // be a constructor declaration with an invalid argument type. Keep
6156 // looking.
6157 if (Tok.is(K: tok::annot_cxxscope))
6158 ConsumeAnnotationToken();
6159 ConsumeToken();
6160
6161 // If this is not a constructor, we must be parsing a declarator,
6162 // which must have one of the following syntactic forms (see the
6163 // grammar extract at the start of ParseDirectDeclarator):
6164 switch (Tok.getKind()) {
6165 case tok::l_paren:
6166 // C(X ( int));
6167 case tok::l_square:
6168 // C(X [ 5]);
6169 // C(X [ [attribute]]);
6170 case tok::coloncolon:
6171 // C(X :: Y);
6172 // C(X :: *p);
6173 // Assume this isn't a constructor, rather than assuming it's a
6174 // constructor with an unnamed parameter of an ill-formed type.
6175 break;
6176
6177 case tok::r_paren:
6178 // C(X )
6179
6180 // Skip past the right-paren and any following attributes to get to
6181 // the function body or trailing-return-type.
6182 ConsumeParen();
6183 SkipCXX11Attributes();
6184
6185 if (DeductionGuide) {
6186 // C(X) -> ... is a deduction guide.
6187 IsConstructor = Tok.is(K: tok::arrow);
6188 break;
6189 }
6190 if (Tok.is(K: tok::colon) || Tok.is(K: tok::kw_try)) {
6191 // Assume these were meant to be constructors:
6192 // C(X) : (the name of a bit-field cannot be parenthesized).
6193 // C(X) try (this is otherwise ill-formed).
6194 IsConstructor = true;
6195 }
6196 if (Tok.is(K: tok::semi) || Tok.is(K: tok::l_brace)) {
6197 // If we have a constructor name within the class definition,
6198 // assume these were meant to be constructors:
6199 // C(X) {
6200 // C(X) ;
6201 // ... because otherwise we would be declaring a non-static data
6202 // member that is ill-formed because it's of the same type as its
6203 // surrounding class.
6204 //
6205 // FIXME: We can actually do this whether or not the name is qualified,
6206 // because if it is qualified in this context it must be being used as
6207 // a constructor name.
6208 // currently, so we're somewhat conservative here.
6209 IsConstructor = IsUnqualified;
6210 }
6211 break;
6212
6213 default:
6214 IsConstructor = true;
6215 break;
6216 }
6217 }
6218 return IsConstructor;
6219}
6220
6221void Parser::ParseTypeQualifierListOpt(
6222 DeclSpec &DS, unsigned AttrReqs, bool AtomicOrPtrauthAllowed,
6223 bool IdentifierRequired, llvm::function_ref<void()> CodeCompletionHandler) {
6224 if ((AttrReqs & AR_CXX11AttributesParsed) &&
6225 isAllowedCXX11AttributeSpecifier()) {
6226 ParsedAttributes Attrs(AttrFactory);
6227 ParseCXX11Attributes(attrs&: Attrs);
6228 DS.takeAttributesAppendingingFrom(attrs&: Attrs);
6229 }
6230
6231 SourceLocation EndLoc;
6232
6233 while (true) {
6234 bool isInvalid = false;
6235 const char *PrevSpec = nullptr;
6236 unsigned DiagID = 0;
6237 SourceLocation Loc = Tok.getLocation();
6238
6239 switch (Tok.getKind()) {
6240 case tok::code_completion:
6241 cutOffParsing();
6242 if (CodeCompletionHandler)
6243 CodeCompletionHandler();
6244 else
6245 Actions.CodeCompletion().CodeCompleteTypeQualifiers(DS);
6246 return;
6247
6248 case tok::kw_const:
6249 isInvalid = DS.SetTypeQual(T: DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
6250 Lang: getLangOpts());
6251 break;
6252 case tok::kw_volatile:
6253 isInvalid = DS.SetTypeQual(T: DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
6254 Lang: getLangOpts());
6255 break;
6256 case tok::kw_restrict:
6257 isInvalid = DS.SetTypeQual(T: DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
6258 Lang: getLangOpts());
6259 break;
6260 case tok::kw___ob_wrap:
6261 if (!getLangOpts().OverflowBehaviorTypes) {
6262 Diag(Loc, DiagID: diag::warn_overflow_behavior_keyword_disabled)
6263 << tok::getKeywordSpelling(Kind: Tok.getKind());
6264 break;
6265 }
6266 isInvalid = DS.SetOverflowBehavior(
6267 Kind: OverflowBehaviorType::OverflowBehaviorKind::Wrap, Loc, PrevSpec,
6268 DiagID);
6269 break;
6270 case tok::kw___ob_trap:
6271 if (!getLangOpts().OverflowBehaviorTypes) {
6272 Diag(Loc, DiagID: diag::warn_overflow_behavior_keyword_disabled)
6273 << tok::getKeywordSpelling(Kind: Tok.getKind());
6274 break;
6275 }
6276 isInvalid = DS.SetOverflowBehavior(
6277 Kind: OverflowBehaviorType::OverflowBehaviorKind::Trap, Loc, PrevSpec,
6278 DiagID);
6279 break;
6280 case tok::kw__Atomic:
6281 if (!AtomicOrPtrauthAllowed)
6282 goto DoneWithTypeQuals;
6283 diagnoseUseOfC11Keyword(Tok);
6284 isInvalid = DS.SetTypeQual(T: DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
6285 Lang: getLangOpts());
6286 break;
6287
6288 // OpenCL qualifiers:
6289 case tok::kw_private:
6290 if (!getLangOpts().OpenCL)
6291 goto DoneWithTypeQuals;
6292 [[fallthrough]];
6293 case tok::kw___private:
6294 case tok::kw___global:
6295 case tok::kw___local:
6296 case tok::kw___constant:
6297 case tok::kw___generic:
6298 case tok::kw___read_only:
6299 case tok::kw___write_only:
6300 case tok::kw___read_write:
6301 ParseOpenCLQualifiers(Attrs&: DS.getAttributes());
6302 break;
6303
6304 case tok::kw_groupshared:
6305 case tok::kw_in:
6306 case tok::kw_inout:
6307 case tok::kw_out:
6308 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
6309 ParseHLSLQualifiers(Attrs&: DS.getAttributes());
6310 continue;
6311
6312 // __ptrauth qualifier.
6313 case tok::kw___ptrauth:
6314 if (!AtomicOrPtrauthAllowed)
6315 goto DoneWithTypeQuals;
6316 ParsePtrauthQualifier(Attrs&: DS.getAttributes());
6317 EndLoc = PrevTokLocation;
6318 continue;
6319
6320 case tok::kw___unaligned:
6321 isInvalid = DS.SetTypeQual(T: DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
6322 Lang: getLangOpts());
6323 break;
6324 case tok::kw___uptr:
6325 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
6326 // with the MS modifier keyword.
6327 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
6328 IdentifierRequired && DS.isEmpty() && NextToken().is(K: tok::semi)) {
6329 if (TryKeywordIdentFallback(DisableKeyword: false))
6330 continue;
6331 }
6332 [[fallthrough]];
6333 case tok::kw___sptr:
6334 case tok::kw___w64:
6335 case tok::kw___ptr64:
6336 case tok::kw___ptr32:
6337 case tok::kw___cdecl:
6338 case tok::kw___stdcall:
6339 case tok::kw___fastcall:
6340 case tok::kw___thiscall:
6341 case tok::kw___regcall:
6342 case tok::kw___vectorcall:
6343 if (AttrReqs & AR_DeclspecAttributesParsed) {
6344 ParseMicrosoftTypeAttributes(attrs&: DS.getAttributes());
6345 continue;
6346 }
6347 goto DoneWithTypeQuals;
6348
6349 case tok::kw___funcref:
6350 ParseWebAssemblyFuncrefTypeAttribute(attrs&: DS.getAttributes());
6351 continue;
6352
6353 case tok::kw___pascal:
6354 if (AttrReqs & AR_VendorAttributesParsed) {
6355 ParseBorlandTypeAttributes(attrs&: DS.getAttributes());
6356 continue;
6357 }
6358 goto DoneWithTypeQuals;
6359
6360 // Nullability type specifiers.
6361 case tok::kw__Nonnull:
6362 case tok::kw__Nullable:
6363 case tok::kw__Nullable_result:
6364 case tok::kw__Null_unspecified:
6365 ParseNullabilityTypeSpecifiers(attrs&: DS.getAttributes());
6366 continue;
6367
6368 // Objective-C 'kindof' types.
6369 case tok::kw___kindof:
6370 DS.getAttributes().addNew(attrName: Tok.getIdentifierInfo(), attrRange: Loc,
6371 scope: AttributeScopeInfo(), args: nullptr, numArgs: 0,
6372 form: tok::kw___kindof);
6373 (void)ConsumeToken();
6374 continue;
6375
6376 case tok::kw___attribute:
6377 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
6378 // When GNU attributes are expressly forbidden, diagnose their usage.
6379 Diag(Tok, DiagID: diag::err_attributes_not_allowed);
6380
6381 // Parse the attributes even if they are rejected to ensure that error
6382 // recovery is graceful.
6383 if (AttrReqs & AR_GNUAttributesParsed ||
6384 AttrReqs & AR_GNUAttributesParsedAndRejected) {
6385 ParseGNUAttributes(Attrs&: DS.getAttributes());
6386 continue; // do *not* consume the next token!
6387 }
6388 // otherwise, FALL THROUGH!
6389 [[fallthrough]];
6390 default:
6391 DoneWithTypeQuals:
6392 // If this is not a type-qualifier token, we're done reading type
6393 // qualifiers. First verify that DeclSpec's are consistent.
6394 DS.Finish(S&: Actions, Policy: Actions.getASTContext().getPrintingPolicy());
6395 if (EndLoc.isValid())
6396 DS.SetRangeEnd(EndLoc);
6397 return;
6398 }
6399
6400 // If the specifier combination wasn't legal, issue a diagnostic.
6401 if (isInvalid) {
6402 assert(PrevSpec && "Method did not return previous specifier!");
6403 Diag(Tok, DiagID) << PrevSpec;
6404 }
6405 EndLoc = ConsumeToken();
6406 }
6407}
6408
6409void Parser::ParseDeclarator(Declarator &D) {
6410 /// This implements the 'declarator' production in the C grammar, then checks
6411 /// for well-formedness and issues diagnostics.
6412 Actions.runWithSufficientStackSpace(Loc: D.getBeginLoc(), Fn: [&] {
6413 ParseDeclaratorInternal(D, DirectDeclParser: &Parser::ParseDirectDeclarator);
6414 });
6415}
6416
6417static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
6418 DeclaratorContext TheContext) {
6419 if (Kind == tok::star || Kind == tok::caret)
6420 return true;
6421
6422 // OpenCL 2.0 and later define this keyword.
6423 if (Kind == tok::kw_pipe && Lang.OpenCL &&
6424 Lang.getOpenCLCompatibleVersion() >= 200)
6425 return true;
6426
6427 if (!Lang.CPlusPlus)
6428 return false;
6429
6430 if (Kind == tok::amp)
6431 return true;
6432
6433 // We parse rvalue refs in C++03, because otherwise the errors are scary.
6434 // But we must not parse them in conversion-type-ids and new-type-ids, since
6435 // those can be legitimately followed by a && operator.
6436 // (The same thing can in theory happen after a trailing-return-type, but
6437 // since those are a C++11 feature, there is no rejects-valid issue there.)
6438 if (Kind == tok::ampamp)
6439 return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId &&
6440 TheContext != DeclaratorContext::CXXNew);
6441
6442 return false;
6443}
6444
6445// Indicates whether the given declarator is a pipe declarator.
6446static bool isPipeDeclarator(const Declarator &D) {
6447 const unsigned NumTypes = D.getNumTypeObjects();
6448
6449 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
6450 if (DeclaratorChunk::Pipe == D.getTypeObject(i: Idx).Kind)
6451 return true;
6452
6453 return false;
6454}
6455
6456void Parser::ParseDeclaratorInternal(Declarator &D,
6457 DirectDeclParseFunction DirectDeclParser) {
6458 if (Diags.hasAllExtensionsSilenced())
6459 D.setExtension();
6460
6461 // C++ member pointers start with a '::' or a nested-name.
6462 // Member pointers get special handling, since there's no place for the
6463 // scope spec in the generic path below.
6464 if (getLangOpts().CPlusPlus &&
6465 (Tok.is(K: tok::coloncolon) || Tok.is(K: tok::kw_decltype) ||
6466 (Tok.is(K: tok::identifier) &&
6467 (NextToken().is(K: tok::coloncolon) || NextToken().is(K: tok::less))) ||
6468 Tok.is(K: tok::annot_cxxscope))) {
6469 TentativeParsingAction TPA(*this, /*Unannotated=*/true);
6470 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6471 D.getContext() == DeclaratorContext::Member;
6472 CXXScopeSpec SS;
6473 SS.setTemplateParamLists(D.getTemplateParameterLists());
6474
6475 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6476 /*ObjectHasErrors=*/false,
6477 /*EnteringContext=*/false,
6478 /*MayBePseudoDestructor=*/nullptr,
6479 /*IsTypename=*/false, /*LastII=*/nullptr,
6480 /*OnlyNamespace=*/false,
6481 /*InUsingDeclaration=*/false,
6482 /*Disambiguation=*/EnteringContext,
6483 /*IsAddressOfOperand=*/false,
6484 /*IsInDeclarationContext=*/true) ||
6485
6486 SS.isEmpty() || SS.isInvalid() || !EnteringContext ||
6487 Tok.is(K: tok::star)) {
6488 TPA.Commit();
6489 if (SS.isNotEmpty() && Tok.is(K: tok::star)) {
6490 if (SS.isValid()) {
6491 checkCompoundToken(FirstTokLoc: SS.getEndLoc(), FirstTokKind: tok::coloncolon,
6492 Op: CompoundToken::MemberPtr);
6493 }
6494
6495 SourceLocation StarLoc = ConsumeToken();
6496 D.SetRangeEnd(StarLoc);
6497 DeclSpec DS(AttrFactory);
6498 ParseTypeQualifierListOpt(DS);
6499 D.ExtendWithDeclSpec(DS);
6500
6501 // Recurse to parse whatever is left.
6502 Actions.runWithSufficientStackSpace(Loc: D.getBeginLoc(), Fn: [&] {
6503 ParseDeclaratorInternal(D, DirectDeclParser);
6504 });
6505
6506 // Sema will have to catch (syntactically invalid) pointers into global
6507 // scope. It has to catch pointers into namespace scope anyway.
6508 D.AddTypeInfo(TI: DeclaratorChunk::getMemberPointer(
6509 SS, TypeQuals: DS.getTypeQualifiers(), StarLoc, EndLoc: DS.getEndLoc()),
6510 attrs: std::move(DS.getAttributes()),
6511 /*EndLoc=*/SourceLocation());
6512 return;
6513 }
6514 } else {
6515 TPA.Revert();
6516 SS.clear();
6517 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6518 /*ObjectHasErrors=*/false,
6519 /*EnteringContext=*/true);
6520 }
6521
6522 if (SS.isNotEmpty()) {
6523 // The scope spec really belongs to the direct-declarator.
6524 if (D.mayHaveIdentifier())
6525 D.getCXXScopeSpec() = std::move(SS);
6526 else
6527 AnnotateScopeToken(SS, IsNewAnnotation: true);
6528
6529 if (DirectDeclParser)
6530 (this->*DirectDeclParser)(D);
6531 return;
6532 }
6533 }
6534
6535 tok::TokenKind Kind = Tok.getKind();
6536
6537 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclarator(D)) {
6538 DeclSpec DS(AttrFactory);
6539 ParseTypeQualifierListOpt(DS);
6540
6541 D.AddTypeInfo(
6542 TI: DeclaratorChunk::getPipe(TypeQuals: DS.getTypeQualifiers(), Loc: DS.getPipeLoc()),
6543 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
6544 }
6545
6546 // Not a pointer, C++ reference, or block.
6547 if (!isPtrOperatorToken(Kind, Lang: getLangOpts(), TheContext: D.getContext())) {
6548 if (DirectDeclParser)
6549 (this->*DirectDeclParser)(D);
6550 return;
6551 }
6552
6553 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
6554 // '&&' -> rvalue reference
6555 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
6556 D.SetRangeEnd(Loc);
6557
6558 if (Kind == tok::star || Kind == tok::caret) {
6559 // Is a pointer.
6560 DeclSpec DS(AttrFactory);
6561
6562 // GNU attributes are not allowed here in a new-type-id, but Declspec and
6563 // C++11 attributes are allowed.
6564 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
6565 ((D.getContext() != DeclaratorContext::CXXNew)
6566 ? AR_GNUAttributesParsed
6567 : AR_GNUAttributesParsedAndRejected);
6568 ParseTypeQualifierListOpt(DS, AttrReqs: Reqs, /*AtomicOrPtrauthAllowed=*/true,
6569 IdentifierRequired: !D.mayOmitIdentifier());
6570 D.ExtendWithDeclSpec(DS);
6571
6572 // Recursively parse the declarator.
6573 Actions.runWithSufficientStackSpace(
6574 Loc: D.getBeginLoc(), Fn: [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6575 if (Kind == tok::star)
6576 // Remember that we parsed a pointer type, and remember the type-quals.
6577 D.AddTypeInfo(TI: DeclaratorChunk::getPointer(
6578 TypeQuals: DS.getTypeQualifiers(), Loc, ConstQualLoc: DS.getConstSpecLoc(),
6579 VolatileQualLoc: DS.getVolatileSpecLoc(), RestrictQualLoc: DS.getRestrictSpecLoc(),
6580 AtomicQualLoc: DS.getAtomicSpecLoc(), UnalignedQualLoc: DS.getUnalignedSpecLoc(),
6581 OverflowBehaviorLoc: DS.getOverflowBehaviorLoc(), OverflowBehaviorIsWrap: DS.isWrapSpecified()),
6582 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
6583 else
6584 // Remember that we parsed a Block type, and remember the type-quals.
6585 D.AddTypeInfo(
6586 TI: DeclaratorChunk::getBlockPointer(TypeQuals: DS.getTypeQualifiers(), Loc),
6587 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
6588 } else {
6589 // Is a reference
6590 DeclSpec DS(AttrFactory);
6591
6592 // Complain about rvalue references in C++03, but then go on and build
6593 // the declarator.
6594 if (Kind == tok::ampamp)
6595 Diag(Loc, DiagID: getLangOpts().CPlusPlus11 ?
6596 diag::warn_cxx98_compat_rvalue_reference :
6597 diag::ext_rvalue_reference);
6598
6599 // GNU-style and C++11 attributes are allowed here, as is restrict.
6600 ParseTypeQualifierListOpt(DS);
6601 D.ExtendWithDeclSpec(DS);
6602
6603 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
6604 // cv-qualifiers are introduced through the use of a typedef or of a
6605 // template type argument, in which case the cv-qualifiers are ignored.
6606 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
6607 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
6608 Diag(Loc: DS.getConstSpecLoc(),
6609 DiagID: diag::err_invalid_reference_qualifier_application) << "const";
6610 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
6611 Diag(Loc: DS.getVolatileSpecLoc(),
6612 DiagID: diag::err_invalid_reference_qualifier_application) << "volatile";
6613 // 'restrict' is permitted as an extension.
6614 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
6615 Diag(Loc: DS.getAtomicSpecLoc(),
6616 DiagID: diag::err_invalid_reference_qualifier_application) << "_Atomic";
6617 }
6618
6619 // Recursively parse the declarator.
6620 Actions.runWithSufficientStackSpace(
6621 Loc: D.getBeginLoc(), Fn: [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6622
6623 if (D.getNumTypeObjects() > 0) {
6624 // C++ [dcl.ref]p4: There shall be no references to references.
6625 DeclaratorChunk& InnerChunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
6626 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
6627 if (const IdentifierInfo *II = D.getIdentifier())
6628 Diag(Loc: InnerChunk.Loc, DiagID: diag::err_illegal_decl_reference_to_reference)
6629 << II;
6630 else
6631 Diag(Loc: InnerChunk.Loc, DiagID: diag::err_illegal_decl_reference_to_reference)
6632 << "type name";
6633
6634 // Once we've complained about the reference-to-reference, we
6635 // can go ahead and build the (technically ill-formed)
6636 // declarator: reference collapsing will take care of it.
6637 }
6638 }
6639
6640 // Remember that we parsed a reference type.
6641 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: DS.getTypeQualifiers(), Loc,
6642 lvalue: Kind == tok::amp),
6643 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
6644 }
6645}
6646
6647// When correcting from misplaced brackets before the identifier, the location
6648// is saved inside the declarator so that other diagnostic messages can use
6649// them. This extracts and returns that location, or returns the provided
6650// location if a stored location does not exist.
6651static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
6652 SourceLocation Loc) {
6653 if (D.getName().StartLocation.isInvalid() &&
6654 D.getName().EndLocation.isValid())
6655 return D.getName().EndLocation;
6656
6657 return Loc;
6658}
6659
6660void Parser::ParseDirectDeclarator(Declarator &D) {
6661 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
6662
6663 if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
6664 // This might be a C++17 structured binding.
6665 if (Tok.is(K: tok::l_square) && !D.mayOmitIdentifier() &&
6666 D.getCXXScopeSpec().isEmpty())
6667 return ParseDecompositionDeclarator(D);
6668
6669 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
6670 // this context it is a bitfield. Also in range-based for statement colon
6671 // may delimit for-range-declaration.
6672 ColonProtectionRAIIObject X(
6673 *this, D.getContext() == DeclaratorContext::Member ||
6674 (D.getContext() == DeclaratorContext::ForInit &&
6675 getLangOpts().CPlusPlus11));
6676
6677 // ParseDeclaratorInternal might already have parsed the scope.
6678 if (D.getCXXScopeSpec().isEmpty()) {
6679 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6680 D.getContext() == DeclaratorContext::Member;
6681 ParseOptionalCXXScopeSpecifier(
6682 SS&: D.getCXXScopeSpec(), /*ObjectType=*/nullptr,
6683 /*ObjectHasErrors=*/false, EnteringContext);
6684 }
6685
6686 // C++23 [basic.scope.namespace]p1:
6687 // For each non-friend redeclaration or specialization whose target scope
6688 // is or is contained by the scope, the portion after the declarator-id,
6689 // class-head-name, or enum-head-name is also included in the scope.
6690 // C++23 [basic.scope.class]p1:
6691 // For each non-friend redeclaration or specialization whose target scope
6692 // is or is contained by the scope, the portion after the declarator-id,
6693 // class-head-name, or enum-head-name is also included in the scope.
6694 //
6695 // FIXME: We should not be doing this for friend declarations; they have
6696 // their own special lookup semantics specified by [basic.lookup.unqual]p6.
6697 if (D.getCXXScopeSpec().isValid()) {
6698 if (Actions.ShouldEnterDeclaratorScope(S: getCurScope(),
6699 SS: D.getCXXScopeSpec()))
6700 // Change the declaration context for name lookup, until this function
6701 // is exited (and the declarator has been parsed).
6702 DeclScopeObj.EnterDeclaratorScope();
6703 else if (getObjCDeclContext()) {
6704 // Ensure that we don't interpret the next token as an identifier when
6705 // dealing with declarations in an Objective-C container.
6706 D.SetIdentifier(Id: nullptr, IdLoc: Tok.getLocation());
6707 D.setInvalidType(true);
6708 ConsumeToken();
6709 goto PastIdentifier;
6710 }
6711 }
6712
6713 // C++0x [dcl.fct]p14:
6714 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
6715 // parameter-declaration-clause without a preceding comma. In this case,
6716 // the ellipsis is parsed as part of the abstract-declarator if the type
6717 // of the parameter either names a template parameter pack that has not
6718 // been expanded or contains auto; otherwise, it is parsed as part of the
6719 // parameter-declaration-clause.
6720 if (Tok.is(K: tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
6721 !((D.getContext() == DeclaratorContext::Prototype ||
6722 D.getContext() == DeclaratorContext::LambdaExprParameter ||
6723 D.getContext() == DeclaratorContext::BlockLiteral) &&
6724 NextToken().is(K: tok::r_paren) && !D.hasGroupingParens() &&
6725 !Actions.containsUnexpandedParameterPacks(D) &&
6726 D.getDeclSpec().getTypeSpecType() != TST_auto)) {
6727 SourceLocation EllipsisLoc = ConsumeToken();
6728 if (isPtrOperatorToken(Kind: Tok.getKind(), Lang: getLangOpts(), TheContext: D.getContext())) {
6729 // The ellipsis was put in the wrong place. Recover, and explain to
6730 // the user what they should have done.
6731 ParseDeclarator(D);
6732 if (EllipsisLoc.isValid())
6733 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6734 return;
6735 } else
6736 D.setEllipsisLoc(EllipsisLoc);
6737
6738 // The ellipsis can't be followed by a parenthesized declarator. We
6739 // check for that in ParseParenDeclarator, after we have disambiguated
6740 // the l_paren token.
6741 }
6742
6743 if (Tok.isOneOf(Ks: tok::identifier, Ks: tok::kw_operator, Ks: tok::annot_template_id,
6744 Ks: tok::tilde)) {
6745 // We found something that indicates the start of an unqualified-id.
6746 // Parse that unqualified-id.
6747 bool AllowConstructorName;
6748 bool AllowDeductionGuide;
6749 if (D.getDeclSpec().hasTypeSpecifier()) {
6750 AllowConstructorName = false;
6751 AllowDeductionGuide = false;
6752 } else if (D.getCXXScopeSpec().isSet()) {
6753 AllowConstructorName = (D.getContext() == DeclaratorContext::File ||
6754 D.getContext() == DeclaratorContext::Member);
6755 AllowDeductionGuide = false;
6756 } else {
6757 AllowConstructorName = (D.getContext() == DeclaratorContext::Member);
6758 AllowDeductionGuide = (D.getContext() == DeclaratorContext::File ||
6759 D.getContext() == DeclaratorContext::Member);
6760 }
6761
6762 bool HadScope = D.getCXXScopeSpec().isValid();
6763 SourceLocation TemplateKWLoc;
6764 if (ParseUnqualifiedId(SS&: D.getCXXScopeSpec(),
6765 /*ObjectType=*/nullptr,
6766 /*ObjectHadErrors=*/false,
6767 /*EnteringContext=*/true,
6768 /*AllowDestructorName=*/true, AllowConstructorName,
6769 AllowDeductionGuide, TemplateKWLoc: &TemplateKWLoc,
6770 Result&: D.getName()) ||
6771 // Once we're past the identifier, if the scope was bad, mark the
6772 // whole declarator bad.
6773 D.getCXXScopeSpec().isInvalid()) {
6774 D.SetIdentifier(Id: nullptr, IdLoc: Tok.getLocation());
6775 D.setInvalidType(true);
6776 } else {
6777 // ParseUnqualifiedId might have parsed a scope specifier during error
6778 // recovery. If it did so, enter that scope.
6779 if (!HadScope && D.getCXXScopeSpec().isValid() &&
6780 Actions.ShouldEnterDeclaratorScope(S: getCurScope(),
6781 SS: D.getCXXScopeSpec()))
6782 DeclScopeObj.EnterDeclaratorScope();
6783
6784 // Parsed the unqualified-id; update range information and move along.
6785 if (D.getSourceRange().getBegin().isInvalid())
6786 D.SetRangeBegin(D.getName().getSourceRange().getBegin());
6787 D.SetRangeEnd(D.getName().getSourceRange().getEnd());
6788 }
6789 goto PastIdentifier;
6790 }
6791
6792 if (D.getCXXScopeSpec().isNotEmpty()) {
6793 // We have a scope specifier but no following unqualified-id.
6794 Diag(Loc: PP.getLocForEndOfToken(Loc: D.getCXXScopeSpec().getEndLoc()),
6795 DiagID: diag::err_expected_unqualified_id)
6796 << /*C++*/1;
6797 D.SetIdentifier(Id: nullptr, IdLoc: Tok.getLocation());
6798 goto PastIdentifier;
6799 }
6800 } else if (Tok.is(K: tok::identifier) && D.mayHaveIdentifier()) {
6801 assert(!getLangOpts().CPlusPlus &&
6802 "There's a C++-specific check for tok::identifier above");
6803 assert(Tok.getIdentifierInfo() && "Not an identifier?");
6804 D.SetIdentifier(Id: Tok.getIdentifierInfo(), IdLoc: Tok.getLocation());
6805 D.SetRangeEnd(Tok.getLocation());
6806 ConsumeToken();
6807 goto PastIdentifier;
6808 } else if (Tok.is(K: tok::identifier) && !D.mayHaveIdentifier()) {
6809 // We're not allowed an identifier here, but we got one. Try to figure out
6810 // if the user was trying to attach a name to the type, or whether the name
6811 // is some unrelated trailing syntax.
6812 bool DiagnoseIdentifier = false;
6813 if (D.hasGroupingParens())
6814 // An identifier within parens is unlikely to be intended to be anything
6815 // other than a name being "declared".
6816 DiagnoseIdentifier = true;
6817 else if (D.getContext() == DeclaratorContext::TemplateArg)
6818 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
6819 DiagnoseIdentifier =
6820 NextToken().isOneOf(Ks: tok::comma, Ks: tok::greater, Ks: tok::greatergreater);
6821 else if (D.getContext() == DeclaratorContext::AliasDecl ||
6822 D.getContext() == DeclaratorContext::AliasTemplate)
6823 // The most likely error is that the ';' was forgotten.
6824 DiagnoseIdentifier = NextToken().isOneOf(Ks: tok::comma, Ks: tok::semi);
6825 else if ((D.getContext() == DeclaratorContext::TrailingReturn ||
6826 D.getContext() == DeclaratorContext::TrailingReturnVar) &&
6827 !isCXX11VirtSpecifier(Tok))
6828 DiagnoseIdentifier = NextToken().isOneOf(
6829 Ks: tok::comma, Ks: tok::semi, Ks: tok::equal, Ks: tok::l_brace, Ks: tok::kw_try);
6830 if (DiagnoseIdentifier) {
6831 Diag(Loc: Tok.getLocation(), DiagID: diag::err_unexpected_unqualified_id)
6832 << FixItHint::CreateRemoval(RemoveRange: Tok.getLocation());
6833 D.SetIdentifier(Id: nullptr, IdLoc: Tok.getLocation());
6834 ConsumeToken();
6835 goto PastIdentifier;
6836 }
6837 }
6838
6839 if (Tok.is(K: tok::l_paren)) {
6840 // If this might be an abstract-declarator followed by a direct-initializer,
6841 // check whether this is a valid declarator chunk. If it can't be, assume
6842 // that it's an initializer instead.
6843 if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
6844 RevertingTentativeParsingAction PA(*this);
6845 if (TryParseDeclarator(mayBeAbstract: true, mayHaveIdentifier: D.mayHaveIdentifier(), mayHaveDirectInit: true,
6846 mayHaveTrailingReturnType: D.getDeclSpec().getTypeSpecType() == TST_auto) ==
6847 TPResult::False) {
6848 D.SetIdentifier(Id: nullptr, IdLoc: Tok.getLocation());
6849 goto PastIdentifier;
6850 }
6851 }
6852
6853 // direct-declarator: '(' declarator ')'
6854 // direct-declarator: '(' attributes declarator ')'
6855 // Example: 'char (*X)' or 'int (*XX)(void)'
6856 ParseParenDeclarator(D);
6857
6858 // If the declarator was parenthesized, we entered the declarator
6859 // scope when parsing the parenthesized declarator, then exited
6860 // the scope already. Re-enter the scope, if we need to.
6861 if (D.getCXXScopeSpec().isSet()) {
6862 // If there was an error parsing parenthesized declarator, declarator
6863 // scope may have been entered before. Don't do it again.
6864 if (!D.isInvalidType() &&
6865 Actions.ShouldEnterDeclaratorScope(S: getCurScope(),
6866 SS: D.getCXXScopeSpec()))
6867 // Change the declaration context for name lookup, until this function
6868 // is exited (and the declarator has been parsed).
6869 DeclScopeObj.EnterDeclaratorScope();
6870 }
6871 } else if (D.mayOmitIdentifier()) {
6872 // This could be something simple like "int" (in which case the declarator
6873 // portion is empty), if an abstract-declarator is allowed.
6874 D.SetIdentifier(Id: nullptr, IdLoc: Tok.getLocation());
6875
6876 // The grammar for abstract-pack-declarator does not allow grouping parens.
6877 // FIXME: Revisit this once core issue 1488 is resolved.
6878 if (D.hasEllipsis() && D.hasGroupingParens())
6879 Diag(Loc: PP.getLocForEndOfToken(Loc: D.getEllipsisLoc()),
6880 DiagID: diag::ext_abstract_pack_declarator_parens);
6881 } else {
6882 if (Tok.getKind() == tok::annot_pragma_parser_crash)
6883 LLVM_BUILTIN_TRAP;
6884 if (Tok.is(K: tok::l_square))
6885 return ParseMisplacedBracketDeclarator(D);
6886 if (D.getContext() == DeclaratorContext::Member) {
6887 // Objective-C++: Detect C++ keywords and try to prevent further errors by
6888 // treating these keyword as valid member names.
6889 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
6890 !Tok.isAnnotation() && Tok.getIdentifierInfo() &&
6891 Tok.getIdentifierInfo()->isCPlusPlusKeyword(LangOpts: getLangOpts())) {
6892 Diag(Loc: getMissingDeclaratorIdLoc(D, Loc: Tok.getLocation()),
6893 DiagID: diag::err_expected_member_name_or_semi_objcxx_keyword)
6894 << Tok.getIdentifierInfo()
6895 << (D.getDeclSpec().isEmpty() ? SourceRange()
6896 : D.getDeclSpec().getSourceRange());
6897 D.SetIdentifier(Id: Tok.getIdentifierInfo(), IdLoc: Tok.getLocation());
6898 D.SetRangeEnd(Tok.getLocation());
6899 ConsumeToken();
6900 goto PastIdentifier;
6901 }
6902 Diag(Loc: getMissingDeclaratorIdLoc(D, Loc: Tok.getLocation()),
6903 DiagID: diag::err_expected_member_name_or_semi)
6904 << (D.getDeclSpec().isEmpty() ? SourceRange()
6905 : D.getDeclSpec().getSourceRange());
6906 } else {
6907 if (Tok.getKind() == tok::TokenKind::kw_while) {
6908 Diag(Tok, DiagID: diag::err_while_loop_outside_of_a_function);
6909 } else if (getLangOpts().CPlusPlus) {
6910 if (Tok.isOneOf(Ks: tok::period, Ks: tok::arrow))
6911 Diag(Tok, DiagID: diag::err_invalid_operator_on_type) << Tok.is(K: tok::arrow);
6912 else {
6913 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
6914 if (Tok.isAtStartOfLine() && Loc.isValid())
6915 Diag(Loc: PP.getLocForEndOfToken(Loc), DiagID: diag::err_expected_unqualified_id)
6916 << getLangOpts().CPlusPlus;
6917 else
6918 Diag(Loc: getMissingDeclaratorIdLoc(D, Loc: Tok.getLocation()),
6919 DiagID: diag::err_expected_unqualified_id)
6920 << getLangOpts().CPlusPlus;
6921 }
6922 } else {
6923 Diag(Loc: getMissingDeclaratorIdLoc(D, Loc: Tok.getLocation()),
6924 DiagID: diag::err_expected_either)
6925 << tok::identifier << tok::l_paren;
6926 }
6927 }
6928 D.SetIdentifier(Id: nullptr, IdLoc: Tok.getLocation());
6929 D.setInvalidType(true);
6930 }
6931
6932 PastIdentifier:
6933 assert(D.isPastIdentifier() &&
6934 "Haven't past the location of the identifier yet?");
6935
6936 // Don't parse attributes unless we have parsed an unparenthesized name.
6937 if (D.hasName() && !D.getNumTypeObjects())
6938 MaybeParseCXX11Attributes(D);
6939
6940 while (true) {
6941 if (Tok.is(K: tok::l_paren)) {
6942 bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
6943 // Enter function-declaration scope, limiting any declarators to the
6944 // function prototype scope, including parameter declarators.
6945 ParseScope PrototypeScope(
6946 this, Scope::FunctionPrototypeScope | Scope::DeclScope |
6947 (IsFunctionDeclaration ? Scope::FunctionDeclarationScope
6948 : Scope::NoScope));
6949
6950 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
6951 // In such a case, check if we actually have a function declarator; if it
6952 // is not, the declarator has been fully parsed.
6953 bool IsAmbiguous = false;
6954 if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
6955 // C++2a [temp.res]p5
6956 // A qualified-id is assumed to name a type if
6957 // - [...]
6958 // - it is a decl-specifier of the decl-specifier-seq of a
6959 // - [...]
6960 // - parameter-declaration in a member-declaration [...]
6961 // - parameter-declaration in a declarator of a function or function
6962 // template declaration whose declarator-id is qualified [...]
6963 auto AllowImplicitTypename = ImplicitTypenameContext::No;
6964 if (D.getCXXScopeSpec().isSet())
6965 AllowImplicitTypename =
6966 (ImplicitTypenameContext)Actions.isDeclaratorFunctionLike(D);
6967 else if (D.getContext() == DeclaratorContext::Member) {
6968 AllowImplicitTypename = ImplicitTypenameContext::Yes;
6969 }
6970
6971 // The name of the declarator, if any, is tentatively declared within
6972 // a possible direct initializer.
6973 TentativelyDeclaredIdentifiers.push_back(Elt: D.getIdentifier());
6974 bool IsFunctionDecl =
6975 isCXXFunctionDeclarator(IsAmbiguous: &IsAmbiguous, AllowImplicitTypename);
6976 TentativelyDeclaredIdentifiers.pop_back();
6977 if (!IsFunctionDecl)
6978 break;
6979 }
6980 ParsedAttributes attrs(AttrFactory);
6981 BalancedDelimiterTracker T(*this, tok::l_paren);
6982 T.consumeOpen();
6983 if (IsFunctionDeclaration)
6984 Actions.ActOnStartFunctionDeclarationDeclarator(D,
6985 TemplateParameterDepth);
6986 ParseFunctionDeclarator(D, FirstArgAttrs&: attrs, Tracker&: T, IsAmbiguous);
6987 if (IsFunctionDeclaration)
6988 Actions.ActOnFinishFunctionDeclarationDeclarator(D);
6989 PrototypeScope.Exit();
6990 } else if (Tok.is(K: tok::l_square)) {
6991 ParseBracketDeclarator(D);
6992 } else if (Tok.isRegularKeywordAttribute()) {
6993 // For consistency with attribute parsing.
6994 Diag(Tok, DiagID: diag::err_keyword_not_allowed) << Tok.getIdentifierInfo();
6995 bool TakesArgs = doesKeywordAttributeTakeArgs(Kind: Tok.getKind());
6996 ConsumeToken();
6997 if (TakesArgs) {
6998 BalancedDelimiterTracker T(*this, tok::l_paren);
6999 if (!T.consumeOpen())
7000 T.skipToEnd();
7001 }
7002 } else if (Tok.is(K: tok::kw_requires) && D.hasGroupingParens()) {
7003 // This declarator is declaring a function, but the requires clause is
7004 // in the wrong place:
7005 // void (f() requires true);
7006 // instead of
7007 // void f() requires true;
7008 // or
7009 // void (f()) requires true;
7010 Diag(Tok, DiagID: diag::err_requires_clause_inside_parens);
7011 ConsumeToken();
7012 ExprResult TrailingRequiresClause =
7013 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
7014 if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
7015 !D.hasTrailingRequiresClause())
7016 // We're already ill-formed if we got here but we'll accept it anyway.
7017 D.setTrailingRequiresClause(TrailingRequiresClause.get());
7018 } else {
7019 break;
7020 }
7021 }
7022}
7023
7024void Parser::ParseDecompositionDeclarator(Declarator &D) {
7025 assert(Tok.is(tok::l_square));
7026
7027 TentativeParsingAction PA(*this);
7028 BalancedDelimiterTracker T(*this, tok::l_square);
7029 T.consumeOpen();
7030
7031 if (isCXX11AttributeSpecifier() != CXX11AttributeKind::NotAttributeSpecifier)
7032 DiagnoseAndSkipCXX11Attributes();
7033
7034 // If this doesn't look like a structured binding, maybe it's a misplaced
7035 // array declarator.
7036 if (!(Tok.isOneOf(Ks: tok::identifier, Ks: tok::ellipsis) &&
7037 NextToken().isOneOf(Ks: tok::comma, Ks: tok::r_square, Ks: tok::kw_alignas,
7038 Ks: tok::identifier, Ks: tok::l_square, Ks: tok::ellipsis)) &&
7039 !(Tok.is(K: tok::r_square) &&
7040 NextToken().isOneOf(Ks: tok::equal, Ks: tok::l_brace))) {
7041 PA.Revert();
7042 return ParseMisplacedBracketDeclarator(D);
7043 }
7044
7045 SourceLocation PrevEllipsisLoc;
7046 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
7047 while (Tok.isNot(K: tok::r_square)) {
7048 if (!Bindings.empty()) {
7049 if (Tok.is(K: tok::comma))
7050 ConsumeToken();
7051 else {
7052 if (Tok.is(K: tok::identifier)) {
7053 SourceLocation EndLoc = getEndOfPreviousToken();
7054 Diag(Loc: EndLoc, DiagID: diag::err_expected)
7055 << tok::comma << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ",");
7056 } else {
7057 Diag(Tok, DiagID: diag::err_expected_comma_or_rsquare);
7058 }
7059
7060 SkipUntil(Toks: {tok::r_square, tok::comma, tok::identifier, tok::ellipsis},
7061 Flags: StopAtSemi | StopBeforeMatch);
7062 if (Tok.is(K: tok::comma))
7063 ConsumeToken();
7064 else if (Tok.is(K: tok::r_square))
7065 break;
7066 }
7067 }
7068
7069 if (isCXX11AttributeSpecifier() !=
7070 CXX11AttributeKind::NotAttributeSpecifier)
7071 DiagnoseAndSkipCXX11Attributes();
7072
7073 SourceLocation EllipsisLoc;
7074
7075 if (Tok.is(K: tok::ellipsis)) {
7076 Diag(Tok, DiagID: getLangOpts().CPlusPlus26 ? diag::warn_cxx23_compat_binding_pack
7077 : diag::ext_cxx_binding_pack);
7078 if (PrevEllipsisLoc.isValid()) {
7079 Diag(Tok, DiagID: diag::err_binding_multiple_ellipses);
7080 Diag(Loc: PrevEllipsisLoc, DiagID: diag::note_previous_ellipsis);
7081 break;
7082 }
7083 EllipsisLoc = Tok.getLocation();
7084 PrevEllipsisLoc = EllipsisLoc;
7085 ConsumeToken();
7086 }
7087
7088 if (Tok.isNot(K: tok::identifier)) {
7089 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
7090 break;
7091 }
7092
7093 IdentifierInfo *II = Tok.getIdentifierInfo();
7094 SourceLocation Loc = Tok.getLocation();
7095 ConsumeToken();
7096
7097 if (Tok.is(K: tok::ellipsis) && !PrevEllipsisLoc.isValid()) {
7098 DiagnoseMisplacedEllipsis(EllipsisLoc: Tok.getLocation(), CorrectLoc: Loc, AlreadyHasEllipsis: EllipsisLoc.isValid(),
7099 IdentifierHasName: true);
7100 EllipsisLoc = Tok.getLocation();
7101 ConsumeToken();
7102 }
7103
7104 ParsedAttributes Attrs(AttrFactory);
7105 if (isCXX11AttributeSpecifier() !=
7106 CXX11AttributeKind::NotAttributeSpecifier) {
7107 Diag(Tok, DiagID: getLangOpts().CPlusPlus26
7108 ? diag::warn_cxx23_compat_decl_attrs_on_binding
7109 : diag::ext_decl_attrs_on_binding);
7110 MaybeParseCXX11Attributes(Attrs);
7111 }
7112
7113 Bindings.push_back(Elt: {.Name: II, .NameLoc: Loc, .Attrs: std::move(Attrs), .EllipsisLoc: EllipsisLoc});
7114 }
7115
7116 if (Tok.isNot(K: tok::r_square))
7117 // We've already diagnosed a problem here.
7118 T.skipToEnd();
7119 else {
7120 // C++17 does not allow the identifier-list in a structured binding
7121 // to be empty.
7122 if (Bindings.empty())
7123 Diag(Loc: Tok.getLocation(), DiagID: diag::ext_decomp_decl_empty);
7124
7125 T.consumeClose();
7126 }
7127
7128 PA.Commit();
7129
7130 return D.setDecompositionBindings(LSquareLoc: T.getOpenLocation(), Bindings,
7131 RSquareLoc: T.getCloseLocation());
7132}
7133
7134void Parser::ParseParenDeclarator(Declarator &D) {
7135 BalancedDelimiterTracker T(*this, tok::l_paren);
7136 T.consumeOpen();
7137
7138 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
7139
7140 // Eat any attributes before we look at whether this is a grouping or function
7141 // declarator paren. If this is a grouping paren, the attribute applies to
7142 // the type being built up, for example:
7143 // int (__attribute__(()) *x)(long y)
7144 // If this ends up not being a grouping paren, the attribute applies to the
7145 // first argument, for example:
7146 // int (__attribute__(()) int x)
7147 // In either case, we need to eat any attributes to be able to determine what
7148 // sort of paren this is.
7149 //
7150 ParsedAttributes attrs(AttrFactory);
7151 bool RequiresArg = false;
7152 if (Tok.is(K: tok::kw___attribute)) {
7153 ParseGNUAttributes(Attrs&: attrs);
7154
7155 // We require that the argument list (if this is a non-grouping paren) be
7156 // present even if the attribute list was empty.
7157 RequiresArg = true;
7158 }
7159
7160 // Eat any Microsoft extensions.
7161 ParseMicrosoftTypeAttributes(attrs);
7162
7163 // Eat any Borland extensions.
7164 if (Tok.is(K: tok::kw___pascal))
7165 ParseBorlandTypeAttributes(attrs);
7166
7167 // If we haven't past the identifier yet (or where the identifier would be
7168 // stored, if this is an abstract declarator), then this is probably just
7169 // grouping parens. However, if this could be an abstract-declarator, then
7170 // this could also be the start of function arguments (consider 'void()').
7171 bool isGrouping;
7172
7173 if (!D.mayOmitIdentifier()) {
7174 // If this can't be an abstract-declarator, this *must* be a grouping
7175 // paren, because we haven't seen the identifier yet.
7176 isGrouping = true;
7177 } else if (Tok.is(K: tok::r_paren) || // 'int()' is a function.
7178 ((getLangOpts().CPlusPlus || getLangOpts().C23) &&
7179 Tok.is(K: tok::ellipsis) &&
7180 NextToken().is(K: tok::r_paren)) || // C++ int(...)
7181 isDeclarationSpecifier(
7182 AllowImplicitTypename: ImplicitTypenameContext::No) || // 'int(int)' is a function.
7183 isCXX11AttributeSpecifier() !=
7184 CXX11AttributeKind::NotAttributeSpecifier) { // 'int([[]]int)'
7185 // is a function.
7186 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
7187 // considered to be a type, not a K&R identifier-list.
7188 isGrouping = false;
7189 } else {
7190 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
7191 isGrouping = true;
7192 }
7193
7194 // If this is a grouping paren, handle:
7195 // direct-declarator: '(' declarator ')'
7196 // direct-declarator: '(' attributes declarator ')'
7197 if (isGrouping) {
7198 SourceLocation EllipsisLoc = D.getEllipsisLoc();
7199 D.setEllipsisLoc(SourceLocation());
7200
7201 bool hadGroupingParens = D.hasGroupingParens();
7202 D.setGroupingParens(true);
7203 ParseDeclaratorInternal(D, DirectDeclParser: &Parser::ParseDirectDeclarator);
7204 // Match the ')'.
7205 T.consumeClose();
7206 D.AddTypeInfo(
7207 TI: DeclaratorChunk::getParen(LParenLoc: T.getOpenLocation(), RParenLoc: T.getCloseLocation()),
7208 attrs: std::move(attrs), EndLoc: T.getCloseLocation());
7209
7210 D.setGroupingParens(hadGroupingParens);
7211
7212 // An ellipsis cannot be placed outside parentheses.
7213 if (EllipsisLoc.isValid())
7214 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
7215
7216 return;
7217 }
7218
7219 // Okay, if this wasn't a grouping paren, it must be the start of a function
7220 // argument list. Recognize that this declarator will never have an
7221 // identifier (and remember where it would have been), then call into
7222 // ParseFunctionDeclarator to handle of argument list.
7223 D.SetIdentifier(Id: nullptr, IdLoc: Tok.getLocation());
7224
7225 // Enter function-declaration scope, limiting any declarators to the
7226 // function prototype scope, including parameter declarators.
7227 ParseScope PrototypeScope(this,
7228 Scope::FunctionPrototypeScope | Scope::DeclScope |
7229 (D.isFunctionDeclaratorAFunctionDeclaration()
7230 ? Scope::FunctionDeclarationScope
7231 : Scope::NoScope));
7232 ParseFunctionDeclarator(D, FirstArgAttrs&: attrs, Tracker&: T, IsAmbiguous: false, RequiresArg);
7233 PrototypeScope.Exit();
7234}
7235
7236void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
7237 const Declarator &D, const DeclSpec &DS,
7238 std::optional<Sema::CXXThisScopeRAII> &ThisScope) {
7239 // C++11 [expr.prim.general]p3:
7240 // If a declaration declares a member function or member function
7241 // template of a class X, the expression this is a prvalue of type
7242 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
7243 // and the end of the function-definition, member-declarator, or
7244 // declarator.
7245 // FIXME: currently, "static" case isn't handled correctly.
7246 bool IsCXX11MemberFunction =
7247 getLangOpts().CPlusPlus11 &&
7248 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7249 (D.getContext() == DeclaratorContext::Member
7250 ? !D.getDeclSpec().isFriendSpecified()
7251 : D.getContext() == DeclaratorContext::File &&
7252 D.getCXXScopeSpec().isValid() &&
7253 Actions.CurContext->isRecord());
7254 if (!IsCXX11MemberFunction)
7255 return;
7256
7257 Qualifiers Q = Qualifiers::fromCVRUMask(CVRU: DS.getTypeQualifiers());
7258 if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
7259 Q.addConst();
7260 // FIXME: Collect C++ address spaces.
7261 // If there are multiple different address spaces, the source is invalid.
7262 // Carry on using the first addr space for the qualifiers of 'this'.
7263 // The diagnostic will be given later while creating the function
7264 // prototype for the method.
7265 if (getLangOpts().OpenCLCPlusPlus) {
7266 for (ParsedAttr &attr : DS.getAttributes()) {
7267 LangAS ASIdx = attr.asOpenCLLangAS();
7268 if (ASIdx != LangAS::Default) {
7269 Q.addAddressSpace(space: ASIdx);
7270 break;
7271 }
7272 }
7273 }
7274 ThisScope.emplace(args&: Actions, args: dyn_cast<CXXRecordDecl>(Val: Actions.CurContext), args&: Q,
7275 args&: IsCXX11MemberFunction);
7276}
7277
7278void Parser::ParseFunctionDeclarator(Declarator &D,
7279 ParsedAttributes &FirstArgAttrs,
7280 BalancedDelimiterTracker &Tracker,
7281 bool IsAmbiguous,
7282 bool RequiresArg) {
7283 assert(getCurScope()->isFunctionPrototypeScope() &&
7284 "Should call from a Function scope");
7285 // lparen is already consumed!
7286 assert(D.isPastIdentifier() && "Should not call before identifier!");
7287
7288 // This should be true when the function has typed arguments.
7289 // Otherwise, it is treated as a K&R-style function.
7290 bool HasProto = false;
7291 // Build up an array of information about the parsed arguments.
7292 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
7293 // Remember where we see an ellipsis, if any.
7294 SourceLocation EllipsisLoc;
7295
7296 DeclSpec DS(AttrFactory);
7297 bool RefQualifierIsLValueRef = true;
7298 SourceLocation RefQualifierLoc;
7299 ExceptionSpecificationType ESpecType = EST_None;
7300 SourceRange ESpecRange;
7301 SmallVector<ParsedType, 2> DynamicExceptions;
7302 SmallVector<SourceRange, 2> DynamicExceptionRanges;
7303 ExprResult NoexceptExpr;
7304 CachedTokens *ExceptionSpecTokens = nullptr;
7305 ParsedAttributes FnAttrs(AttrFactory);
7306 TypeResult TrailingReturnType;
7307 SourceLocation TrailingReturnTypeLoc;
7308
7309 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
7310 EndLoc is the end location for the function declarator.
7311 They differ for trailing return types. */
7312 SourceLocation StartLoc, LocalEndLoc, EndLoc;
7313 SourceLocation LParenLoc, RParenLoc;
7314 LParenLoc = Tracker.getOpenLocation();
7315 StartLoc = LParenLoc;
7316
7317 if (isFunctionDeclaratorIdentifierList()) {
7318 if (RequiresArg)
7319 Diag(Tok, DiagID: diag::err_argument_required_after_attribute);
7320
7321 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
7322
7323 Tracker.consumeClose();
7324 RParenLoc = Tracker.getCloseLocation();
7325 LocalEndLoc = RParenLoc;
7326 EndLoc = RParenLoc;
7327
7328 // If there are attributes following the identifier list, parse them and
7329 // prohibit them.
7330 MaybeParseCXX11Attributes(Attrs&: FnAttrs);
7331 ProhibitAttributes(Attrs&: FnAttrs);
7332 } else {
7333 if (Tok.isNot(K: tok::r_paren))
7334 ParseParameterDeclarationClause(D, attrs&: FirstArgAttrs, ParamInfo, EllipsisLoc);
7335 else if (RequiresArg)
7336 Diag(Tok, DiagID: diag::err_argument_required_after_attribute);
7337
7338 // OpenCL disallows functions without a prototype, but it doesn't enforce
7339 // strict prototypes as in C23 because it allows a function definition to
7340 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
7341 HasProto = ParamInfo.size() || getLangOpts().requiresStrictPrototypes() ||
7342 getLangOpts().OpenCL;
7343
7344 // If we have the closing ')', eat it.
7345 Tracker.consumeClose();
7346 RParenLoc = Tracker.getCloseLocation();
7347 LocalEndLoc = RParenLoc;
7348 EndLoc = RParenLoc;
7349
7350 if (getLangOpts().CPlusPlus) {
7351 // FIXME: Accept these components in any order, and produce fixits to
7352 // correct the order if the user gets it wrong. Ideally we should deal
7353 // with the pure-specifier in the same way.
7354
7355 // Parse cv-qualifier-seq[opt].
7356 ParseTypeQualifierListOpt(
7357 DS, AttrReqs: AR_NoAttributesParsed,
7358 /*AtomicOrPtrauthAllowed=*/false,
7359 /*IdentifierRequired=*/false, CodeCompletionHandler: [&]() {
7360 Actions.CodeCompletion().CodeCompleteFunctionQualifiers(DS, D);
7361 });
7362 if (!DS.getSourceRange().getEnd().isInvalid()) {
7363 EndLoc = DS.getSourceRange().getEnd();
7364 }
7365
7366 // Parse ref-qualifier[opt].
7367 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
7368 EndLoc = RefQualifierLoc;
7369
7370 std::optional<Sema::CXXThisScopeRAII> ThisScope;
7371 InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
7372
7373 // C++ [class.mem.general]p8:
7374 // A complete-class context of a class (template) is a
7375 // - function body,
7376 // - default argument,
7377 // - default template argument,
7378 // - noexcept-specifier, or
7379 // - default member initializer
7380 // within the member-specification of the class or class template.
7381 //
7382 // Parse exception-specification[opt]. If we are in the
7383 // member-specification of a class or class template, this is a
7384 // complete-class context and parsing of the noexcept-specifier should be
7385 // delayed (even if this is a friend declaration).
7386 bool Delayed = D.getContext() == DeclaratorContext::Member &&
7387 D.isFunctionDeclaratorAFunctionDeclaration();
7388 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
7389 GetLookAheadToken(N: 0).is(K: tok::kw_noexcept) &&
7390 GetLookAheadToken(N: 1).is(K: tok::l_paren) &&
7391 GetLookAheadToken(N: 2).is(K: tok::kw_noexcept) &&
7392 GetLookAheadToken(N: 3).is(K: tok::l_paren) &&
7393 GetLookAheadToken(N: 4).is(K: tok::identifier) &&
7394 GetLookAheadToken(N: 4).getIdentifierInfo()->isStr(Str: "swap")) {
7395 // HACK: We've got an exception-specification
7396 // noexcept(noexcept(swap(...)))
7397 // or
7398 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
7399 // on a 'swap' member function. This is a libstdc++ bug; the lookup
7400 // for 'swap' will only find the function we're currently declaring,
7401 // whereas it expects to find a non-member swap through ADL. Turn off
7402 // delayed parsing to give it a chance to find what it expects.
7403 Delayed = false;
7404 }
7405 ESpecType = tryParseExceptionSpecification(Delayed,
7406 SpecificationRange&: ESpecRange,
7407 DynamicExceptions,
7408 DynamicExceptionRanges,
7409 NoexceptExpr,
7410 ExceptionSpecTokens);
7411 if (ESpecType != EST_None)
7412 EndLoc = ESpecRange.getEnd();
7413
7414 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
7415 // after the exception-specification.
7416 MaybeParseCXX11Attributes(Attrs&: FnAttrs);
7417
7418 // Parse trailing-return-type[opt].
7419 LocalEndLoc = EndLoc;
7420 if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::arrow)) {
7421 Diag(Tok, DiagID: diag::warn_cxx98_compat_trailing_return_type);
7422 if (D.getDeclSpec().getTypeSpecType() == TST_auto)
7423 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
7424 LocalEndLoc = Tok.getLocation();
7425 SourceRange Range;
7426 TrailingReturnType =
7427 ParseTrailingReturnType(Range, MayBeFollowedByDirectInit: D.mayBeFollowedByCXXDirectInit());
7428 TrailingReturnTypeLoc = Range.getBegin();
7429 EndLoc = Range.getEnd();
7430 }
7431 } else {
7432 MaybeParseCXX11Attributes(Attrs&: FnAttrs);
7433 }
7434 }
7435
7436 // Collect non-parameter declarations from the prototype if this is a function
7437 // declaration. They will be moved into the scope of the function. Only do
7438 // this in C and not C++, where the decls will continue to live in the
7439 // surrounding context.
7440 SmallVector<NamedDecl *, 0> DeclsInPrototype;
7441 if (getCurScope()->isFunctionDeclarationScope() && !getLangOpts().CPlusPlus) {
7442 for (Decl *D : getCurScope()->decls()) {
7443 NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
7444 if (!ND || isa<ParmVarDecl>(Val: ND))
7445 continue;
7446 DeclsInPrototype.push_back(Elt: ND);
7447 }
7448 // Sort DeclsInPrototype based on raw encoding of the source location.
7449 // Scope::decls() is iterating over a SmallPtrSet so sort the Decls before
7450 // moving to DeclContext. This provides a stable ordering for traversing
7451 // Decls in DeclContext, which is important for tasks like ASTWriter for
7452 // deterministic output.
7453 llvm::sort(C&: DeclsInPrototype, Comp: [](Decl *D1, Decl *D2) {
7454 return D1->getLocation().getRawEncoding() <
7455 D2->getLocation().getRawEncoding();
7456 });
7457 }
7458
7459 // Remember that we parsed a function type, and remember the attributes.
7460 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(
7461 HasProto, IsAmbiguous, LParenLoc, Params: ParamInfo.data(),
7462 NumParams: ParamInfo.size(), EllipsisLoc, RParenLoc,
7463 RefQualifierIsLvalueRef: RefQualifierIsLValueRef, RefQualifierLoc,
7464 /*MutableLoc=*/SourceLocation(),
7465 ESpecType, ESpecRange, Exceptions: DynamicExceptions.data(),
7466 ExceptionRanges: DynamicExceptionRanges.data(), NumExceptions: DynamicExceptions.size(),
7467 NoexceptExpr: NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
7468 ExceptionSpecTokens, DeclsInPrototype, LocalRangeBegin: StartLoc,
7469 LocalRangeEnd: LocalEndLoc, TheDeclarator&: D, TrailingReturnType, TrailingReturnTypeLoc,
7470 MethodQualifiers: &DS),
7471 attrs: std::move(FnAttrs), EndLoc);
7472}
7473
7474bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
7475 SourceLocation &RefQualifierLoc) {
7476 if (Tok.isOneOf(Ks: tok::amp, Ks: tok::ampamp)) {
7477 Diag(Tok, DiagID: getLangOpts().CPlusPlus11 ?
7478 diag::warn_cxx98_compat_ref_qualifier :
7479 diag::ext_ref_qualifier);
7480
7481 RefQualifierIsLValueRef = Tok.is(K: tok::amp);
7482 RefQualifierLoc = ConsumeToken();
7483 return true;
7484 }
7485 return false;
7486}
7487
7488bool Parser::isFunctionDeclaratorIdentifierList() {
7489 return !getLangOpts().requiresStrictPrototypes()
7490 && Tok.is(K: tok::identifier)
7491 && !TryAltiVecVectorToken()
7492 // K&R identifier lists can't have typedefs as identifiers, per C99
7493 // 6.7.5.3p11.
7494 && (TryAnnotateTypeOrScopeToken() || !Tok.is(K: tok::annot_typename))
7495 // Identifier lists follow a really simple grammar: the identifiers can
7496 // be followed *only* by a ", identifier" or ")". However, K&R
7497 // identifier lists are really rare in the brave new modern world, and
7498 // it is very common for someone to typo a type in a non-K&R style
7499 // list. If we are presented with something like: "void foo(intptr x,
7500 // float y)", we don't want to start parsing the function declarator as
7501 // though it is a K&R style declarator just because intptr is an
7502 // invalid type.
7503 //
7504 // To handle this, we check to see if the token after the first
7505 // identifier is a "," or ")". Only then do we parse it as an
7506 // identifier list.
7507 && (!Tok.is(K: tok::eof) &&
7508 (NextToken().is(K: tok::comma) || NextToken().is(K: tok::r_paren)));
7509}
7510
7511void Parser::ParseFunctionDeclaratorIdentifierList(
7512 Declarator &D,
7513 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
7514 // We should never reach this point in C23 or C++.
7515 assert(!getLangOpts().requiresStrictPrototypes() &&
7516 "Cannot parse an identifier list in C23 or C++");
7517
7518 // If there was no identifier specified for the declarator, either we are in
7519 // an abstract-declarator, or we are in a parameter declarator which was found
7520 // to be abstract. In abstract-declarators, identifier lists are not valid:
7521 // diagnose this.
7522 if (!D.getIdentifier())
7523 Diag(Tok, DiagID: diag::ext_ident_list_in_param);
7524
7525 // Maintain an efficient lookup of params we have seen so far.
7526 llvm::SmallPtrSet<const IdentifierInfo *, 16> ParamsSoFar;
7527
7528 do {
7529 // If this isn't an identifier, report the error and skip until ')'.
7530 if (Tok.isNot(K: tok::identifier)) {
7531 Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
7532 SkipUntil(T: tok::r_paren, Flags: StopAtSemi | StopBeforeMatch);
7533 // Forget we parsed anything.
7534 ParamInfo.clear();
7535 return;
7536 }
7537
7538 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
7539
7540 // Reject 'typedef int y; int test(x, y)', but continue parsing.
7541 if (Actions.getTypeName(II: *ParmII, NameLoc: Tok.getLocation(), S: getCurScope()))
7542 Diag(Tok, DiagID: diag::err_unexpected_typedef_ident) << ParmII;
7543
7544 // Verify that the argument identifier has not already been mentioned.
7545 if (!ParamsSoFar.insert(Ptr: ParmII).second) {
7546 Diag(Tok, DiagID: diag::err_param_redefinition) << ParmII;
7547 } else {
7548 // Remember this identifier in ParamInfo.
7549 ParamInfo.push_back(Elt: DeclaratorChunk::ParamInfo(ParmII,
7550 Tok.getLocation(),
7551 nullptr));
7552 }
7553
7554 // Eat the identifier.
7555 ConsumeToken();
7556 // The list continues if we see a comma.
7557 } while (TryConsumeToken(Expected: tok::comma));
7558}
7559
7560void Parser::ParseParameterDeclarationClause(
7561 DeclaratorContext DeclaratorCtx, ParsedAttributes &FirstArgAttrs,
7562 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
7563 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration) {
7564
7565 // Avoid exceeding the maximum function scope depth.
7566 // See https://bugs.llvm.org/show_bug.cgi?id=19607
7567 // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
7568 // getFunctionPrototypeDepth() - 1.
7569 if (getCurScope()->getFunctionPrototypeDepth() - 1 >
7570 ParmVarDecl::getMaxFunctionScopeDepth()) {
7571 Diag(Loc: Tok.getLocation(), DiagID: diag::err_function_scope_depth_exceeded)
7572 << ParmVarDecl::getMaxFunctionScopeDepth();
7573 cutOffParsing();
7574 return;
7575 }
7576
7577 // C++2a [temp.res]p5
7578 // A qualified-id is assumed to name a type if
7579 // - [...]
7580 // - it is a decl-specifier of the decl-specifier-seq of a
7581 // - [...]
7582 // - parameter-declaration in a member-declaration [...]
7583 // - parameter-declaration in a declarator of a function or function
7584 // template declaration whose declarator-id is qualified [...]
7585 // - parameter-declaration in a lambda-declarator [...]
7586 auto AllowImplicitTypename = ImplicitTypenameContext::No;
7587 if (DeclaratorCtx == DeclaratorContext::Member ||
7588 DeclaratorCtx == DeclaratorContext::LambdaExpr ||
7589 DeclaratorCtx == DeclaratorContext::RequiresExpr ||
7590 IsACXXFunctionDeclaration) {
7591 AllowImplicitTypename = ImplicitTypenameContext::Yes;
7592 }
7593
7594 do {
7595 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
7596 // before deciding this was a parameter-declaration-clause.
7597 if (TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc))
7598 break;
7599
7600 // Parse the declaration-specifiers.
7601 // Just use the ParsingDeclaration "scope" of the declarator.
7602 DeclSpec DS(AttrFactory);
7603
7604 ParsedAttributes ArgDeclAttrs(AttrFactory);
7605 ParsedAttributes ArgDeclSpecAttrs(AttrFactory);
7606
7607 if (FirstArgAttrs.Range.isValid()) {
7608 // If the caller parsed attributes for the first argument, add them now.
7609 // Take them so that we only apply the attributes to the first parameter.
7610 // We have already started parsing the decl-specifier sequence, so don't
7611 // parse any parameter-declaration pieces that precede it.
7612 ArgDeclSpecAttrs.takeAllPrependingFrom(Other&: FirstArgAttrs);
7613 } else {
7614 // Parse any C++11 attributes.
7615 MaybeParseCXX11Attributes(Attrs&: ArgDeclAttrs);
7616
7617 // Skip any Microsoft attributes before a param.
7618 MaybeParseMicrosoftAttributes(Attrs&: ArgDeclSpecAttrs);
7619 }
7620
7621 SourceLocation DSStart = Tok.getLocation();
7622
7623 // Parse a C++23 Explicit Object Parameter
7624 // We do that in all language modes to produce a better diagnostic.
7625 SourceLocation ThisLoc;
7626 if (getLangOpts().CPlusPlus && Tok.is(K: tok::kw_this))
7627 ThisLoc = ConsumeToken();
7628
7629 ParsedTemplateInfo TemplateInfo;
7630 ParseDeclarationSpecifiers(DS, TemplateInfo, AS: AS_none,
7631 DSContext: DeclSpecContext::DSC_normal,
7632 /*LateAttrs=*/nullptr, AllowImplicitTypename);
7633
7634 DS.takeAttributesAppendingingFrom(attrs&: ArgDeclSpecAttrs);
7635
7636 // Parse the declarator. This is "PrototypeContext" or
7637 // "LambdaExprParameterContext", because we must accept either
7638 // 'declarator' or 'abstract-declarator' here.
7639 Declarator ParmDeclarator(DS, ArgDeclAttrs,
7640 DeclaratorCtx == DeclaratorContext::RequiresExpr
7641 ? DeclaratorContext::RequiresExpr
7642 : DeclaratorCtx == DeclaratorContext::LambdaExpr
7643 ? DeclaratorContext::LambdaExprParameter
7644 : DeclaratorContext::Prototype);
7645 ParseDeclarator(D&: ParmDeclarator);
7646
7647 if (ThisLoc.isValid())
7648 ParmDeclarator.SetRangeBegin(ThisLoc);
7649
7650 // Parse GNU attributes, if present.
7651 MaybeParseGNUAttributes(D&: ParmDeclarator);
7652 if (getLangOpts().HLSL)
7653 MaybeParseHLSLAnnotations(Attrs&: DS.getAttributes());
7654
7655 if (Tok.is(K: tok::kw_requires)) {
7656 // User tried to define a requires clause in a parameter declaration,
7657 // which is surely not a function declaration.
7658 // void f(int (*g)(int, int) requires true);
7659 Diag(Tok,
7660 DiagID: diag::err_requires_clause_on_declarator_not_declaring_a_function);
7661 ConsumeToken();
7662 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
7663 }
7664
7665 // Remember this parsed parameter in ParamInfo.
7666 const IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
7667
7668 // DefArgToks is used when the parsing of default arguments needs
7669 // to be delayed.
7670 std::unique_ptr<CachedTokens> DefArgToks;
7671
7672 // If no parameter was specified, verify that *something* was specified,
7673 // otherwise we have a missing type and identifier.
7674 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
7675 ParmDeclarator.getNumTypeObjects() == 0) {
7676 // Completely missing, emit error.
7677 Diag(Loc: DSStart, DiagID: diag::err_missing_param);
7678 } else {
7679 // Otherwise, we have something. Add it and let semantic analysis try
7680 // to grok it and add the result to the ParamInfo we are building.
7681
7682 // Last chance to recover from a misplaced ellipsis in an attempted
7683 // parameter pack declaration.
7684 if (Tok.is(K: tok::ellipsis) &&
7685 (NextToken().isNot(K: tok::r_paren) ||
7686 (!ParmDeclarator.getEllipsisLoc().isValid() &&
7687 !Actions.isUnexpandedParameterPackPermitted())) &&
7688 Actions.containsUnexpandedParameterPacks(D&: ParmDeclarator))
7689 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc: ConsumeToken(), D&: ParmDeclarator);
7690
7691 // Now we are at the point where declarator parsing is finished.
7692 //
7693 // Try to catch keywords in place of the identifier in a declarator, and
7694 // in particular the common case where:
7695 // 1 identifier comes at the end of the declarator
7696 // 2 if the identifier is dropped, the declarator is valid but anonymous
7697 // (no identifier)
7698 // 3 declarator parsing succeeds, and then we have a trailing keyword,
7699 // which is never valid in a param list (e.g. missing a ',')
7700 // And we can't handle this in ParseDeclarator because in general keywords
7701 // may be allowed to follow the declarator. (And in some cases there'd be
7702 // better recovery like inserting punctuation). ParseDeclarator is just
7703 // treating this as an anonymous parameter, and fortunately at this point
7704 // we've already almost done that.
7705 //
7706 // We care about case 1) where the declarator type should be known, and
7707 // the identifier should be null.
7708 if (!ParmDeclarator.isInvalidType() && !ParmDeclarator.hasName() &&
7709 Tok.isNot(K: tok::raw_identifier) && !Tok.isAnnotation() &&
7710 Tok.getIdentifierInfo() &&
7711 Tok.getIdentifierInfo()->isKeyword(LangOpts: getLangOpts())) {
7712 Diag(Tok, DiagID: diag::err_keyword_as_parameter) << PP.getSpelling(Tok);
7713 // Consume the keyword.
7714 ConsumeToken();
7715 }
7716
7717 // We can only store so many parameters
7718 // Skip until the the end of the parameter list, ignoring
7719 // parameters that would overflow.
7720 if (ParamInfo.size() == Type::FunctionTypeNumParamsLimit) {
7721 Diag(Loc: ParmDeclarator.getBeginLoc(),
7722 DiagID: diag::err_function_parameter_limit_exceeded);
7723 SkipUntil(T: tok::r_paren, Flags: SkipUntilFlags::StopBeforeMatch);
7724 break;
7725 }
7726
7727 // Inform the actions module about the parameter declarator, so it gets
7728 // added to the current scope.
7729 Decl *Param =
7730 Actions.ActOnParamDeclarator(S: getCurScope(), D&: ParmDeclarator, ExplicitThisLoc: ThisLoc);
7731 // Parse the default argument, if any. We parse the default
7732 // arguments in all dialects; the semantic analysis in
7733 // ActOnParamDefaultArgument will reject the default argument in
7734 // C.
7735 if (Tok.is(K: tok::equal)) {
7736 SourceLocation EqualLoc = Tok.getLocation();
7737
7738 // Parse the default argument
7739 if (DeclaratorCtx == DeclaratorContext::Member) {
7740 // If we're inside a class definition, cache the tokens
7741 // corresponding to the default argument. We'll actually parse
7742 // them when we see the end of the class definition.
7743 DefArgToks.reset(p: new CachedTokens);
7744
7745 SourceLocation ArgStartLoc = NextToken().getLocation();
7746 ConsumeAndStoreInitializer(Toks&: *DefArgToks,
7747 CIK: CachedInitKind::DefaultArgument);
7748 Actions.ActOnParamUnparsedDefaultArgument(param: Param, EqualLoc,
7749 ArgLoc: ArgStartLoc);
7750 } else {
7751 // Consume the '='.
7752 ConsumeToken();
7753
7754 // The default argument may contain a lambda whose body triggers
7755 // MaybeDestroyTemplateIds at the end of the inner statements; avoid
7756 // destroying parsed template-ids that may still be referenced by
7757 // the enclosing declarator (e.g. a template-id in the function
7758 // name or other parameters).
7759 DelayTemplateIdDestructionRAII DontDestructTemplateIds(
7760 *this, /*DelayTemplateIdDestruction=*/true);
7761
7762 // The argument isn't actually potentially evaluated unless it is
7763 // used.
7764 EnterExpressionEvaluationContext Eval(
7765 Actions,
7766 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
7767 Param);
7768
7769 ExprResult DefArgResult;
7770 if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::l_brace)) {
7771 Diag(Tok, DiagID: diag::warn_cxx98_compat_generalized_initializer_lists);
7772 DefArgResult = ParseBraceInitializer();
7773 } else {
7774 if (Tok.is(K: tok::l_paren) && NextToken().is(K: tok::l_brace)) {
7775 Diag(Tok, DiagID: diag::err_stmt_expr_in_default_arg) << 0;
7776 Actions.ActOnParamDefaultArgumentError(param: Param, EqualLoc,
7777 /*DefaultArg=*/nullptr);
7778 // Skip the statement expression and continue parsing
7779 SkipUntil(T: tok::comma, Flags: StopBeforeMatch);
7780 continue;
7781 }
7782 DefArgResult = ParseAssignmentExpression();
7783 }
7784 if (DefArgResult.isInvalid()) {
7785 Actions.ActOnParamDefaultArgumentError(param: Param, EqualLoc,
7786 /*DefaultArg=*/nullptr);
7787 SkipUntil(T1: tok::comma, T2: tok::r_paren, Flags: StopAtSemi | StopBeforeMatch);
7788 } else {
7789 // Inform the actions module about the default argument
7790 Actions.ActOnParamDefaultArgument(param: Param, EqualLoc,
7791 defarg: DefArgResult.get());
7792 }
7793 }
7794 }
7795
7796 ParamInfo.push_back(Elt: DeclaratorChunk::ParamInfo(ParmII,
7797 ParmDeclarator.getIdentifierLoc(),
7798 Param, std::move(DefArgToks)));
7799 }
7800
7801 if (TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc)) {
7802 if (getLangOpts().CPlusPlus26) {
7803 // C++26 [dcl.dcl.fct]p3:
7804 // A parameter-declaration-clause of the form
7805 // parameter-list '...' is deprecated.
7806 Diag(Loc: EllipsisLoc, DiagID: diag::warn_deprecated_missing_comma_before_ellipsis)
7807 << FixItHint::CreateInsertion(InsertionLoc: EllipsisLoc, Code: ", ");
7808 }
7809
7810 if (!getLangOpts().CPlusPlus) {
7811 // We have ellipsis without a preceding ',', which is ill-formed
7812 // in C. Complain and provide the fix.
7813 Diag(Loc: EllipsisLoc, DiagID: diag::err_missing_comma_before_ellipsis)
7814 << FixItHint::CreateInsertion(InsertionLoc: EllipsisLoc, Code: ", ");
7815 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
7816 Actions.containsUnexpandedParameterPacks(D&: ParmDeclarator)) {
7817 // It looks like this was supposed to be a parameter pack. Warn and
7818 // point out where the ellipsis should have gone.
7819 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
7820 Diag(Loc: EllipsisLoc, DiagID: diag::warn_misplaced_ellipsis_vararg)
7821 << ParmEllipsis.isValid() << ParmEllipsis;
7822 if (ParmEllipsis.isValid()) {
7823 Diag(Loc: ParmEllipsis,
7824 DiagID: diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
7825 } else {
7826 Diag(Loc: ParmDeclarator.getIdentifierLoc(),
7827 DiagID: diag::note_misplaced_ellipsis_vararg_add_ellipsis)
7828 << FixItHint::CreateInsertion(InsertionLoc: ParmDeclarator.getIdentifierLoc(),
7829 Code: "...")
7830 << !ParmDeclarator.hasName();
7831 }
7832 Diag(Loc: EllipsisLoc, DiagID: diag::note_misplaced_ellipsis_vararg_add_comma)
7833 << FixItHint::CreateInsertion(InsertionLoc: EllipsisLoc, Code: ", ");
7834 }
7835
7836 // We can't have any more parameters after an ellipsis.
7837 break;
7838 }
7839
7840 // If the next token is a comma, consume it and keep reading arguments.
7841 } while (TryConsumeToken(Expected: tok::comma));
7842}
7843
7844void Parser::ParseBracketDeclarator(Declarator &D) {
7845 if (CheckProhibitedCXX11Attribute())
7846 return;
7847
7848 BalancedDelimiterTracker T(*this, tok::l_square);
7849 T.consumeOpen();
7850
7851 // C array syntax has many features, but by-far the most common is [] and [4].
7852 // This code does a fast path to handle some of the most obvious cases.
7853 if (Tok.getKind() == tok::r_square) {
7854 T.consumeClose();
7855 ParsedAttributes attrs(AttrFactory);
7856 MaybeParseCXX11Attributes(Attrs&: attrs);
7857
7858 // Remember that we parsed the empty array type.
7859 D.AddTypeInfo(TI: DeclaratorChunk::getArray(TypeQuals: 0, isStatic: false, isStar: false, NumElts: nullptr,
7860 LBLoc: T.getOpenLocation(),
7861 RBLoc: T.getCloseLocation()),
7862 attrs: std::move(attrs), EndLoc: T.getCloseLocation());
7863 return;
7864 } else if (Tok.getKind() == tok::numeric_constant &&
7865 GetLookAheadToken(N: 1).is(K: tok::r_square)) {
7866 // [4] is very common. Parse the numeric constant expression.
7867 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, UDLScope: getCurScope()));
7868 ConsumeToken();
7869
7870 T.consumeClose();
7871 ParsedAttributes attrs(AttrFactory);
7872 MaybeParseCXX11Attributes(Attrs&: attrs);
7873
7874 // Remember that we parsed a array type, and remember its features.
7875 D.AddTypeInfo(TI: DeclaratorChunk::getArray(TypeQuals: 0, isStatic: false, isStar: false, NumElts: ExprRes.get(),
7876 LBLoc: T.getOpenLocation(),
7877 RBLoc: T.getCloseLocation()),
7878 attrs: std::move(attrs), EndLoc: T.getCloseLocation());
7879 return;
7880 } else if (Tok.getKind() == tok::code_completion) {
7881 cutOffParsing();
7882 Actions.CodeCompletion().CodeCompleteBracketDeclarator(S: getCurScope());
7883 return;
7884 }
7885
7886 // If valid, this location is the position where we read the 'static' keyword.
7887 SourceLocation StaticLoc;
7888 TryConsumeToken(Expected: tok::kw_static, Loc&: StaticLoc);
7889
7890 // If there is a type-qualifier-list, read it now.
7891 // Type qualifiers in an array subscript are a C99 feature.
7892 DeclSpec DS(AttrFactory);
7893 ParseTypeQualifierListOpt(DS, AttrReqs: AR_CXX11AttributesParsed);
7894
7895 // If we haven't already read 'static', check to see if there is one after the
7896 // type-qualifier-list.
7897 if (!StaticLoc.isValid())
7898 TryConsumeToken(Expected: tok::kw_static, Loc&: StaticLoc);
7899
7900 // Handle "direct-declarator [ type-qual-list[opt] * ]".
7901 bool isStar = false;
7902 ExprResult NumElements;
7903
7904 // Handle the case where we have '[*]' as the array size. However, a leading
7905 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
7906 // the token after the star is a ']'. Since stars in arrays are
7907 // infrequent, use of lookahead is not costly here.
7908 if (Tok.is(K: tok::star) && GetLookAheadToken(N: 1).is(K: tok::r_square)) {
7909 ConsumeToken(); // Eat the '*'.
7910
7911 if (StaticLoc.isValid()) {
7912 Diag(Loc: StaticLoc, DiagID: diag::err_unspecified_vla_size_with_static);
7913 StaticLoc = SourceLocation(); // Drop the static.
7914 }
7915 isStar = true;
7916 } else if (Tok.isNot(K: tok::r_square)) {
7917 // Note, in C89, this production uses the constant-expr production instead
7918 // of assignment-expr. The only difference is that assignment-expr allows
7919 // things like '=' and '*='. Sema rejects these in C89 mode because they
7920 // are not i-c-e's, so we don't need to distinguish between the two here.
7921
7922 // Parse the constant-expression or assignment-expression now (depending
7923 // on dialect).
7924 if (getLangOpts().CPlusPlus) {
7925 NumElements = ParseArrayBoundExpression();
7926 } else {
7927 EnterExpressionEvaluationContext Unevaluated(
7928 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7929 NumElements = ParseAssignmentExpression();
7930 }
7931 } else {
7932 if (StaticLoc.isValid()) {
7933 Diag(Loc: StaticLoc, DiagID: diag::err_unspecified_size_with_static);
7934 StaticLoc = SourceLocation(); // Drop the static.
7935 }
7936 }
7937
7938 // If there was an error parsing the assignment-expression, recover.
7939 if (NumElements.isInvalid()) {
7940 D.setInvalidType(true);
7941 // If the expression was invalid, skip it.
7942 SkipUntil(T: tok::r_square, Flags: StopAtSemi);
7943 return;
7944 }
7945
7946 T.consumeClose();
7947
7948 MaybeParseCXX11Attributes(Attrs&: DS.getAttributes());
7949
7950 // Remember that we parsed a array type, and remember its features.
7951 D.AddTypeInfo(
7952 TI: DeclaratorChunk::getArray(TypeQuals: DS.getTypeQualifiers(), isStatic: StaticLoc.isValid(),
7953 isStar, NumElts: NumElements.get(), LBLoc: T.getOpenLocation(),
7954 RBLoc: T.getCloseLocation()),
7955 attrs: std::move(DS.getAttributes()), EndLoc: T.getCloseLocation());
7956}
7957
7958void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
7959 assert(Tok.is(tok::l_square) && "Missing opening bracket");
7960 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
7961
7962 SourceLocation StartBracketLoc = Tok.getLocation();
7963 Declarator TempDeclarator(D.getDeclSpec(), ParsedAttributesView::none(),
7964 D.getContext());
7965
7966 while (Tok.is(K: tok::l_square)) {
7967 ParseBracketDeclarator(D&: TempDeclarator);
7968 }
7969
7970 // Stuff the location of the start of the brackets into the Declarator.
7971 // The diagnostics from ParseDirectDeclarator will make more sense if
7972 // they use this location instead.
7973 if (Tok.is(K: tok::semi))
7974 D.getName().EndLocation = StartBracketLoc;
7975
7976 SourceLocation SuggestParenLoc = Tok.getLocation();
7977
7978 // Now that the brackets are removed, try parsing the declarator again.
7979 ParseDeclaratorInternal(D, DirectDeclParser: &Parser::ParseDirectDeclarator);
7980
7981 // Something went wrong parsing the brackets, in which case,
7982 // ParseBracketDeclarator has emitted an error, and we don't need to emit
7983 // one here.
7984 if (TempDeclarator.getNumTypeObjects() == 0)
7985 return;
7986
7987 // Determine if parens will need to be suggested in the diagnostic.
7988 bool NeedParens = false;
7989 if (D.getNumTypeObjects() != 0) {
7990 switch (D.getTypeObject(i: D.getNumTypeObjects() - 1).Kind) {
7991 case DeclaratorChunk::Pointer:
7992 case DeclaratorChunk::Reference:
7993 case DeclaratorChunk::BlockPointer:
7994 case DeclaratorChunk::MemberPointer:
7995 case DeclaratorChunk::Pipe:
7996 NeedParens = true;
7997 break;
7998 case DeclaratorChunk::Array:
7999 case DeclaratorChunk::Function:
8000 case DeclaratorChunk::Paren:
8001 break;
8002 }
8003 }
8004
8005 if (NeedParens) {
8006 // Create a DeclaratorChunk for the inserted parens.
8007 SourceLocation EndLoc = PP.getLocForEndOfToken(Loc: D.getEndLoc());
8008 D.AddTypeInfo(TI: DeclaratorChunk::getParen(LParenLoc: SuggestParenLoc, RParenLoc: EndLoc),
8009 EndLoc: SourceLocation());
8010 }
8011
8012 // Adding back the bracket info to the end of the Declarator.
8013 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
8014 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
8015 D.AddTypeInfo(TI: Chunk, OtherPool&: TempDeclarator.getAttributePool(), EndLoc: SourceLocation());
8016 }
8017
8018 // The missing name would have been diagnosed in ParseDirectDeclarator.
8019 // If parentheses are required, always suggest them.
8020 if (!D.hasName() && !NeedParens)
8021 return;
8022
8023 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
8024
8025 // Generate the move bracket error message.
8026 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
8027 SourceLocation EndLoc = PP.getLocForEndOfToken(Loc: D.getEndLoc());
8028
8029 if (NeedParens) {
8030 Diag(Loc: EndLoc, DiagID: diag::err_brackets_go_after_unqualified_id)
8031 << getLangOpts().CPlusPlus
8032 << FixItHint::CreateInsertion(InsertionLoc: SuggestParenLoc, Code: "(")
8033 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")")
8034 << FixItHint::CreateInsertionFromRange(
8035 InsertionLoc: EndLoc, FromRange: CharSourceRange(BracketRange, true))
8036 << FixItHint::CreateRemoval(RemoveRange: BracketRange);
8037 } else {
8038 Diag(Loc: EndLoc, DiagID: diag::err_brackets_go_after_unqualified_id)
8039 << getLangOpts().CPlusPlus
8040 << FixItHint::CreateInsertionFromRange(
8041 InsertionLoc: EndLoc, FromRange: CharSourceRange(BracketRange, true))
8042 << FixItHint::CreateRemoval(RemoveRange: BracketRange);
8043 }
8044}
8045
8046void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
8047 assert(Tok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
8048 "Not a typeof specifier");
8049
8050 bool IsUnqual = Tok.is(K: tok::kw_typeof_unqual);
8051 const IdentifierInfo *II = Tok.getIdentifierInfo();
8052 if (getLangOpts().C23 && !II->getName().starts_with(Prefix: "__"))
8053 Diag(Loc: Tok.getLocation(), DiagID: diag::warn_c23_compat_keyword) << Tok.getName();
8054
8055 Token OpTok = Tok;
8056 SourceLocation StartLoc = ConsumeToken();
8057 bool HasParens = Tok.is(K: tok::l_paren);
8058
8059 EnterExpressionEvaluationContext Unevaluated(
8060 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
8061 Sema::ReuseLambdaContextDecl);
8062
8063 bool isCastExpr;
8064 ParsedType CastTy;
8065 SourceRange CastRange;
8066 ExprResult Operand =
8067 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange);
8068 if (HasParens)
8069 DS.setTypeArgumentRange(CastRange);
8070
8071 if (CastRange.getEnd().isInvalid())
8072 // FIXME: Not accurate, the range gets one token more than it should.
8073 DS.SetRangeEnd(Tok.getLocation());
8074 else
8075 DS.SetRangeEnd(CastRange.getEnd());
8076
8077 if (isCastExpr) {
8078 if (!CastTy) {
8079 DS.SetTypeSpecError();
8080 return;
8081 }
8082
8083 const char *PrevSpec = nullptr;
8084 unsigned DiagID;
8085 // Check for duplicate type specifiers (e.g. "int typeof(int)").
8086 if (DS.SetTypeSpecType(T: IsUnqual ? DeclSpec::TST_typeof_unqualType
8087 : DeclSpec::TST_typeofType,
8088 Loc: StartLoc, PrevSpec,
8089 DiagID, Rep: CastTy,
8090 Policy: Actions.getASTContext().getPrintingPolicy()))
8091 Diag(Loc: StartLoc, DiagID) << PrevSpec;
8092 return;
8093 }
8094
8095 // If we get here, the operand to the typeof was an expression.
8096 if (Operand.isInvalid()) {
8097 DS.SetTypeSpecError();
8098 return;
8099 }
8100
8101 // We might need to transform the operand if it is potentially evaluated.
8102 Operand = Actions.HandleExprEvaluationContextForTypeof(E: Operand.get());
8103 if (Operand.isInvalid()) {
8104 DS.SetTypeSpecError();
8105 return;
8106 }
8107
8108 const char *PrevSpec = nullptr;
8109 unsigned DiagID;
8110 // Check for duplicate type specifiers (e.g. "int typeof(int)").
8111 if (DS.SetTypeSpecType(T: IsUnqual ? DeclSpec::TST_typeof_unqualExpr
8112 : DeclSpec::TST_typeofExpr,
8113 Loc: StartLoc, PrevSpec,
8114 DiagID, Rep: Operand.get(),
8115 policy: Actions.getASTContext().getPrintingPolicy()))
8116 Diag(Loc: StartLoc, DiagID) << PrevSpec;
8117}
8118
8119void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
8120 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
8121 "Not an atomic specifier");
8122
8123 SourceLocation StartLoc = ConsumeToken();
8124 BalancedDelimiterTracker T(*this, tok::l_paren);
8125 if (T.consumeOpen())
8126 return;
8127
8128 TypeResult Result = ParseTypeName();
8129 if (Result.isInvalid()) {
8130 SkipUntil(T: tok::r_paren, Flags: StopAtSemi);
8131 return;
8132 }
8133
8134 // Match the ')'
8135 T.consumeClose();
8136
8137 if (T.getCloseLocation().isInvalid())
8138 return;
8139
8140 DS.setTypeArgumentRange(T.getRange());
8141 DS.SetRangeEnd(T.getCloseLocation());
8142
8143 const char *PrevSpec = nullptr;
8144 unsigned DiagID;
8145 if (DS.SetTypeSpecType(T: DeclSpec::TST_atomic, Loc: StartLoc, PrevSpec,
8146 DiagID, Rep: Result.get(),
8147 Policy: Actions.getASTContext().getPrintingPolicy()))
8148 Diag(Loc: StartLoc, DiagID) << PrevSpec;
8149}
8150
8151bool Parser::TryAltiVecVectorTokenOutOfLine() {
8152 Token Next = NextToken();
8153 switch (Next.getKind()) {
8154 default: return false;
8155 case tok::kw_short:
8156 case tok::kw_long:
8157 case tok::kw_signed:
8158 case tok::kw_unsigned:
8159 case tok::kw_void:
8160 case tok::kw_char:
8161 case tok::kw_int:
8162 case tok::kw_float:
8163 case tok::kw_double:
8164 case tok::kw_bool:
8165 case tok::kw__Bool:
8166 case tok::kw___bool:
8167 case tok::kw___pixel:
8168 Tok.setKind(tok::kw___vector);
8169 return true;
8170 case tok::identifier:
8171 if (Next.getIdentifierInfo() == Ident_pixel) {
8172 Tok.setKind(tok::kw___vector);
8173 return true;
8174 }
8175 if (Next.getIdentifierInfo() == Ident_bool ||
8176 Next.getIdentifierInfo() == Ident_Bool) {
8177 Tok.setKind(tok::kw___vector);
8178 return true;
8179 }
8180 return false;
8181 }
8182}
8183
8184bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
8185 const char *&PrevSpec, unsigned &DiagID,
8186 bool &isInvalid) {
8187 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
8188 if (Tok.getIdentifierInfo() == Ident_vector) {
8189 Token Next = NextToken();
8190 switch (Next.getKind()) {
8191 case tok::kw_short:
8192 case tok::kw_long:
8193 case tok::kw_signed:
8194 case tok::kw_unsigned:
8195 case tok::kw_void:
8196 case tok::kw_char:
8197 case tok::kw_int:
8198 case tok::kw_float:
8199 case tok::kw_double:
8200 case tok::kw_bool:
8201 case tok::kw__Bool:
8202 case tok::kw___bool:
8203 case tok::kw___pixel:
8204 isInvalid = DS.SetTypeAltiVecVector(isAltiVecVector: true, Loc, PrevSpec, DiagID, Policy);
8205 return true;
8206 case tok::identifier:
8207 if (Next.getIdentifierInfo() == Ident_pixel) {
8208 isInvalid = DS.SetTypeAltiVecVector(isAltiVecVector: true, Loc, PrevSpec, DiagID,Policy);
8209 return true;
8210 }
8211 if (Next.getIdentifierInfo() == Ident_bool ||
8212 Next.getIdentifierInfo() == Ident_Bool) {
8213 isInvalid =
8214 DS.SetTypeAltiVecVector(isAltiVecVector: true, Loc, PrevSpec, DiagID, Policy);
8215 return true;
8216 }
8217 break;
8218 default:
8219 break;
8220 }
8221 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
8222 DS.isTypeAltiVecVector()) {
8223 isInvalid = DS.SetTypeAltiVecPixel(isAltiVecPixel: true, Loc, PrevSpec, DiagID, Policy);
8224 return true;
8225 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
8226 DS.isTypeAltiVecVector()) {
8227 isInvalid = DS.SetTypeAltiVecBool(isAltiVecBool: true, Loc, PrevSpec, DiagID, Policy);
8228 return true;
8229 }
8230 return false;
8231}
8232
8233TypeResult Parser::ParseTypeFromString(StringRef TypeStr, StringRef Context,
8234 SourceLocation IncludeLoc) {
8235 // Consume (unexpanded) tokens up to the end-of-directive.
8236 SmallVector<Token, 4> Tokens;
8237 {
8238 // Create a new buffer from which we will parse the type.
8239 auto &SourceMgr = PP.getSourceManager();
8240 FileID FID = SourceMgr.createFileID(
8241 Buffer: llvm::MemoryBuffer::getMemBufferCopy(InputData: TypeStr, BufferName: Context), FileCharacter: SrcMgr::C_User,
8242 LoadedID: 0, LoadedOffset: 0, IncludeLoc);
8243
8244 // Form a new lexer that references the buffer.
8245 Lexer L(FID, SourceMgr.getBufferOrFake(FID), PP);
8246 L.setParsingPreprocessorDirective(true);
8247
8248 // Lex the tokens from that buffer.
8249 Token Tok;
8250 do {
8251 L.Lex(Result&: Tok);
8252 Tokens.push_back(Elt: Tok);
8253 } while (Tok.isNot(K: tok::eod));
8254 }
8255
8256 // Replace the "eod" token with an "eof" token identifying the end of
8257 // the provided string.
8258 Token &EndToken = Tokens.back();
8259 EndToken.startToken();
8260 EndToken.setKind(tok::eof);
8261 EndToken.setLocation(Tok.getLocation());
8262 EndToken.setEofData(TypeStr.data());
8263
8264 // Add the current token back.
8265 Tokens.push_back(Elt: Tok);
8266
8267 // Enter the tokens into the token stream.
8268 PP.EnterTokenStream(Toks: Tokens, /*DisableMacroExpansion=*/false,
8269 /*IsReinject=*/false);
8270
8271 // Consume the current token so that we'll start parsing the tokens we
8272 // added to the stream.
8273 ConsumeAnyToken();
8274
8275 // Enter a new scope.
8276 ParseScope LocalScope(this, 0);
8277
8278 // Parse the type.
8279 TypeResult Result = ParseTypeName(Range: nullptr);
8280
8281 // Check if we parsed the whole thing.
8282 if (Result.isUsable() &&
8283 (Tok.isNot(K: tok::eof) || Tok.getEofData() != TypeStr.data())) {
8284 Diag(Loc: Tok.getLocation(), DiagID: diag::err_type_unparsed);
8285 }
8286
8287 // There could be leftover tokens (e.g. because of an error).
8288 // Skip through until we reach the 'end of directive' token.
8289 while (Tok.isNot(K: tok::eof))
8290 ConsumeAnyToken();
8291
8292 // Consume the end token.
8293 if (Tok.is(K: tok::eof) && Tok.getEofData() == TypeStr.data())
8294 ConsumeAnyToken();
8295 return Result;
8296}
8297
8298void Parser::DiagnoseBitIntUse(const Token &Tok) {
8299 // If the token is for _ExtInt, diagnose it as being deprecated. Otherwise,
8300 // the token is about _BitInt and gets (potentially) diagnosed as use of an
8301 // extension.
8302 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
8303 "expected either an _ExtInt or _BitInt token!");
8304
8305 SourceLocation Loc = Tok.getLocation();
8306 if (Tok.is(K: tok::kw__ExtInt)) {
8307 Diag(Loc, DiagID: diag::warn_ext_int_deprecated)
8308 << FixItHint::CreateReplacement(RemoveRange: Loc, Code: "_BitInt");
8309 } else {
8310 // In C23 mode, diagnose that the use is not compatible with pre-C23 modes.
8311 // Otherwise, diagnose that the use is a Clang extension.
8312 if (getLangOpts().C23)
8313 Diag(Loc, DiagID: diag::warn_c23_compat_keyword) << Tok.getName();
8314 else
8315 Diag(Loc, DiagID: diag::ext_bit_int) << getLangOpts().CPlusPlus;
8316 }
8317}
8318