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