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