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