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