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 return;
2159
2160 default:
2161 break;
2162 }
2163
2165 }
2166}
2167
2168Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2169 DeclaratorContext Context,
2170 ParsedAttributes &Attrs,
2171 ParsedTemplateInfo &TemplateInfo,
2172 SourceLocation *DeclEnd,
2173 ForRangeInit *FRI) {
2174 // Parse the first declarator.
2175 // Consume all of the attributes from `Attrs` by moving them to our own local
2176 // list. This ensures that we will not attempt to interpret them as statement
2177 // attributes higher up the callchain.
2178 ParsedAttributes LocalAttrs(AttrFactory);
2179 LocalAttrs.takeAllPrependingFrom(Attrs);
2180 ParsingDeclarator D(*this, DS, LocalAttrs, Context);
2181 if (TemplateInfo.TemplateParams)
2182 D.setTemplateParameterLists(*TemplateInfo.TemplateParams);
2183
2184 bool IsTemplateSpecOrInst =
2185 (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation ||
2186 TemplateInfo.Kind == ParsedTemplateKind::ExplicitSpecialization);
2187 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
2188
2189 ParseDeclarator(D);
2190
2191 if (IsTemplateSpecOrInst)
2192 SAC.done();
2193
2194 // Bail out if the first declarator didn't seem well-formed.
2195 if (!D.hasName() && !D.mayOmitIdentifier()) {
2197 return nullptr;
2198 }
2199
2200 if (getLangOpts().HLSL)
2201 while (MaybeParseHLSLAnnotations(D))
2202 ;
2203
2204 if (Tok.is(tok::kw_requires)) {
2205 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
2206 // With abbreviated function templates - we need to explicitly add depth to
2207 // account for the implicit template parameter list induced by the template.
2208 if (!TemplateInfo.TemplateParams && D.getInventedTemplateParameterList())
2209 ++CurTemplateDepthTracker;
2210 ParseTrailingRequiresClauseWithScope(D);
2211 }
2212
2213 // Save late-parsed attributes for now; they need to be parsed in the
2214 // appropriate function scope after the function Decl has been constructed.
2215 // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2216 LateParsedAttrList LateParsedAttrs(true);
2217 if (D.isFunctionDeclarator()) {
2218 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2219
2220 // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2221 // attribute. If we find the keyword here, tell the user to put it
2222 // at the start instead.
2223 if (Tok.is(tok::kw__Noreturn)) {
2224 SourceLocation Loc = ConsumeToken();
2225 const char *PrevSpec;
2226 unsigned DiagID;
2227
2228 // We can offer a fixit if it's valid to mark this function as _Noreturn
2229 // and we don't have any other declarators in this declaration.
2230 bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2231 MaybeParseGNUAttributes(D, &LateParsedAttrs);
2232 Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2233
2234 Diag(Loc, diag::err_c11_noreturn_misplaced)
2235 << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2236 << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2237 : FixItHint());
2238 }
2239
2240 // Check to see if we have a function *definition* which must have a body.
2241 if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
2242 cutOffParsing();
2243 Actions.CodeCompletion().CodeCompleteAfterFunctionEquals(D);
2244 return nullptr;
2245 }
2246 // We're at the point where the parsing of function declarator is finished.
2247 //
2248 // A common error is that users accidently add a virtual specifier
2249 // (e.g. override) in an out-line method definition.
2250 // We attempt to recover by stripping all these specifiers coming after
2251 // the declarator.
2252 while (auto Specifier = isCXX11VirtSpecifier()) {
2253 Diag(Tok, diag::err_virt_specifier_outside_class)
2255 << FixItHint::CreateRemoval(Tok.getLocation());
2256 ConsumeToken();
2257 }
2258 // Look at the next token to make sure that this isn't a function
2259 // declaration. We have to check this because __attribute__ might be the
2260 // start of a function definition in GCC-extended K&R C.
2261 if (!isDeclarationAfterDeclarator()) {
2262
2263 // Function definitions are only allowed at file scope and in C++ classes.
2264 // The C++ inline method definition case is handled elsewhere, so we only
2265 // need to handle the file scope definition case.
2266 if (Context == DeclaratorContext::File) {
2267 if (isStartOfFunctionDefinition(D)) {
2268 // C++23 [dcl.typedef] p1:
2269 // The typedef specifier shall not be [...], and it shall not be
2270 // used in the decl-specifier-seq of a parameter-declaration nor in
2271 // the decl-specifier-seq of a function-definition.
2273 // If the user intended to write 'typename', we should have already
2274 // suggested adding it elsewhere. In any case, recover by ignoring
2275 // 'typedef' and suggest removing it.
2277 diag::err_function_declared_typedef)
2280 }
2281 Decl *TheDecl = nullptr;
2282
2283 if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation) {
2285 // If the declarator-id is not a template-id, issue a diagnostic
2286 // and recover by ignoring the 'template' keyword.
2287 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
2288 TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
2289 &LateParsedAttrs);
2290 } else {
2291 SourceLocation LAngleLoc =
2292 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2294 diag::err_explicit_instantiation_with_definition)
2295 << SourceRange(TemplateInfo.TemplateLoc)
2296 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2297
2298 // Recover as if it were an explicit specialization.
2299 TemplateParameterLists FakedParamLists;
2300 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2301 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, {},
2302 LAngleLoc, nullptr));
2303
2304 TheDecl = ParseFunctionDefinition(
2305 D,
2306 ParsedTemplateInfo(&FakedParamLists,
2307 /*isSpecialization=*/true,
2308 /*lastParameterListWasEmpty=*/true),
2309 &LateParsedAttrs);
2310 }
2311 } else {
2312 TheDecl =
2313 ParseFunctionDefinition(D, TemplateInfo, &LateParsedAttrs);
2314 }
2315
2316 return Actions.ConvertDeclToDeclGroup(TheDecl);
2317 }
2318
2319 if (isDeclarationSpecifier(ImplicitTypenameContext::No) ||
2320 Tok.is(tok::kw_namespace)) {
2321 // If there is an invalid declaration specifier or a namespace
2322 // definition right after the function prototype, then we must be in a
2323 // missing semicolon case where this isn't actually a body. Just fall
2324 // through into the code that handles it as a prototype, and let the
2325 // top-level code handle the erroneous declspec where it would
2326 // otherwise expect a comma or semicolon. Note that
2327 // isDeclarationSpecifier already covers 'inline namespace', since
2328 // 'inline' can be a declaration specifier.
2329 } else {
2330 Diag(Tok, diag::err_expected_fn_body);
2331 SkipUntil(tok::semi);
2332 return nullptr;
2333 }
2334 } else {
2335 if (Tok.is(tok::l_brace)) {
2336 Diag(Tok, diag::err_function_definition_not_allowed);
2338 return nullptr;
2339 }
2340 }
2341 }
2342 }
2343
2344 if (ParseAsmAttributesAfterDeclarator(D))
2345 return nullptr;
2346
2347 // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2348 // must parse and analyze the for-range-initializer before the declaration is
2349 // analyzed.
2350 //
2351 // Handle the Objective-C for-in loop variable similarly, although we
2352 // don't need to parse the container in advance.
2353 if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2354 // If we're parsing an expansion statement, enter its context to ensure
2355 // the declaration ends up in a dependent context. We previously left the
2356 // context of the expansion statement because init-statements should *not*
2357 // be in a dependent context, and only once we get here do we know that this
2358 // is not an init-statement but rather a for-range-declaration.
2359 //
2360 // Note that this is *not* the case if we get here via ParseCXXCondition()
2361 // since if that is called when we parse an expansion statement, we know for
2362 // sure that it has to be the for-range-declaration.
2363 //
2364 // We can't use ContextRAII here since that pushes a new delayed diagnostics
2365 // pool, which causes issues during declaration parsing.
2366 bool EnterContext = FRI->ExpansionStmt &&
2367 Actions.CurContext == FRI->ExpansionStmt->getParent();
2368 if (EnterContext)
2369 Actions.PushDeclContext(nullptr, FRI->ExpansionStmt);
2370 llvm::scope_exit RestoreDeclContext{[&] {
2371 if (EnterContext)
2372 Actions.PopDeclContext();
2373 }};
2374
2375 bool IsForRangeLoopOrExpansionStmt = false;
2376 if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2377 IsForRangeLoopOrExpansionStmt = true;
2378 if (getLangOpts().OpenMP && !FRI->ExpansionStmt)
2379 Actions.OpenMP().startOpenMPCXXRangeFor();
2380
2381 ParseForRangeInitializerAfterColon(*FRI, &DS);
2382 }
2383
2384 Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2385 if (IsForRangeLoopOrExpansionStmt) {
2386 Actions.ActOnCXXForRangeDecl(ThisDecl, FRI->ExpansionStmt);
2387 } else {
2388 // Obj-C for loop
2389 if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2390 VD->setObjCForDecl(true);
2391 }
2392 Actions.FinalizeDeclaration(ThisDecl);
2393 D.complete(ThisDecl);
2394 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2395 }
2396
2397 SmallVector<Decl *, 8> DeclsInGroup;
2398 Decl *FirstDecl =
2399 ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo, FRI);
2400 if (LateParsedAttrs.size() > 0)
2401 ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2402 D.complete(FirstDecl);
2403 if (FirstDecl)
2404 DeclsInGroup.push_back(FirstDecl);
2405
2406 bool ExpectSemi = Context != DeclaratorContext::ForInit;
2407
2408 // If we don't have a comma, it is either the end of the list (a ';') or an
2409 // error, bail out.
2410 SourceLocation CommaLoc;
2411 while (TryConsumeToken(tok::comma, CommaLoc)) {
2412 if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2413 // This comma was followed by a line-break and something which can't be
2414 // the start of a declarator. The comma was probably a typo for a
2415 // semicolon.
2416 Diag(CommaLoc, diag::err_expected_semi_declaration)
2417 << FixItHint::CreateReplacement(CommaLoc, ";");
2418 ExpectSemi = false;
2419 break;
2420 }
2421
2422 // C++23 [temp.pre]p5:
2423 // In a template-declaration, explicit specialization, or explicit
2424 // instantiation the init-declarator-list in the declaration shall
2425 // contain at most one declarator.
2426 if (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate &&
2427 D.isFirstDeclarator()) {
2428 Diag(CommaLoc, diag::err_multiple_template_declarators)
2429 << TemplateInfo.Kind;
2430 }
2431
2432 // Parse the next declarator.
2433 D.clear();
2434 D.setCommaLoc(CommaLoc);
2435
2436 // Accept attributes in an init-declarator. In the first declarator in a
2437 // declaration, these would be part of the declspec. In subsequent
2438 // declarators, they become part of the declarator itself, so that they
2439 // don't apply to declarators after *this* one. Examples:
2440 // short __attribute__((common)) var; -> declspec
2441 // short var __attribute__((common)); -> declarator
2442 // short x, __attribute__((common)) var; -> declarator
2443 MaybeParseGNUAttributes(D);
2444
2445 // MSVC parses but ignores qualifiers after the comma as an extension.
2446 if (getLangOpts().MicrosoftExt)
2447 DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2448
2449 ParseDeclarator(D);
2450
2451 if (getLangOpts().HLSL)
2452 MaybeParseHLSLAnnotations(D);
2453
2454 if (!D.isInvalidType()) {
2455 // C++2a [dcl.decl]p1
2456 // init-declarator:
2457 // declarator initializer[opt]
2458 // declarator requires-clause
2459 if (Tok.is(tok::kw_requires))
2460 ParseTrailingRequiresClauseWithScope(D);
2461 Decl *ThisDecl = ParseDeclarationAfterDeclarator(D, TemplateInfo);
2462 D.complete(ThisDecl);
2463 if (ThisDecl)
2464 DeclsInGroup.push_back(ThisDecl);
2465 }
2466 }
2467
2468 if (DeclEnd)
2469 *DeclEnd = Tok.getLocation();
2470
2471 if (ExpectSemi && ExpectAndConsumeSemi(
2472 Context == DeclaratorContext::File
2473 ? diag::err_invalid_token_after_toplevel_declarator
2474 : diag::err_expected_semi_declaration)) {
2475 // Okay, there was no semicolon and one was expected. If we see a
2476 // declaration specifier, just assume it was missing and continue parsing.
2477 // Otherwise things are very confused and we skip to recover.
2478 if (!isDeclarationSpecifier(ImplicitTypenameContext::No))
2480 }
2481
2482 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2483}
2484
2485bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2486 // If a simple-asm-expr is present, parse it.
2487 if (Tok.is(tok::kw_asm)) {
2488 SourceLocation Loc;
2489 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2490 if (AsmLabel.isInvalid()) {
2491 SkipUntil(tok::semi, StopBeforeMatch);
2492 return true;
2493 }
2494
2495 D.setAsmLabel(AsmLabel.get());
2496 D.SetRangeEnd(Loc);
2497 }
2498
2499 MaybeParseGNUAttributes(D);
2500 return false;
2501}
2502
2503Decl *Parser::ParseDeclarationAfterDeclarator(
2504 Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2505 if (ParseAsmAttributesAfterDeclarator(D))
2506 return nullptr;
2507
2508 return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2509}
2510
2511Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2512 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2513 // RAII type used to track whether we're inside an initializer.
2514 struct InitializerScopeRAII {
2515 Parser &P;
2516 Declarator &D;
2517 Decl *ThisDecl;
2518 bool Entered;
2519
2520 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2521 : P(P), D(D), ThisDecl(ThisDecl), Entered(false) {
2522 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2523 Scope *S = nullptr;
2524 if (D.getCXXScopeSpec().isSet()) {
2525 P.EnterScope(0);
2526 S = P.getCurScope();
2527 }
2528 if (ThisDecl && !ThisDecl->isInvalidDecl()) {
2529 P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2530 Entered = true;
2531 }
2532 }
2533 }
2534 ~InitializerScopeRAII() {
2535 if (ThisDecl && P.getLangOpts().CPlusPlus) {
2536 Scope *S = nullptr;
2537 if (D.getCXXScopeSpec().isSet())
2538 S = P.getCurScope();
2539
2540 if (Entered)
2541 P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2542 if (S)
2543 P.ExitScope();
2544 }
2545 ThisDecl = nullptr;
2546 }
2547 };
2548
2549 enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
2550 InitKind TheInitKind;
2551 // If a '==' or '+=' is found, suggest a fixit to '='.
2552 if (isTokenEqualOrEqualTypo())
2553 TheInitKind = InitKind::Equal;
2554 else if (getLangOpts().CPlusPlus && Tok.is(tok::l_paren))
2555 TheInitKind = InitKind::CXXDirect;
2556 else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2557 (!CurParsedObjCImpl || !D.isFunctionDeclarator()))
2558 TheInitKind = InitKind::CXXBraced;
2559 else
2560 TheInitKind = InitKind::Uninitialized;
2561 if (TheInitKind != InitKind::Uninitialized)
2563
2564 // Inform Sema that we just parsed this declarator.
2565 Decl *ThisDecl = nullptr;
2566 Decl *OuterDecl = nullptr;
2567 switch (TemplateInfo.Kind) {
2569 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2570 break;
2571
2574 ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2575 *TemplateInfo.TemplateParams,
2576 D);
2577 if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2578 // Re-direct this decl to refer to the templated decl so that we can
2579 // initialize it.
2580 ThisDecl = VT->getTemplatedDecl();
2581 OuterDecl = VT;
2582 }
2583 break;
2584 }
2586 if (Tok.is(tok::semi)) {
2587 DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2588 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2589 if (ThisRes.isInvalid()) {
2590 SkipUntil(tok::semi, StopBeforeMatch);
2591 return nullptr;
2592 }
2593 ThisDecl = ThisRes.get();
2594 } else {
2595 // FIXME: This check should be for a variable template instantiation only.
2596
2597 // Check that this is a valid instantiation
2599 // If the declarator-id is not a template-id, issue a diagnostic and
2600 // recover by ignoring the 'template' keyword.
2601 Diag(Tok, diag::err_template_defn_explicit_instantiation)
2602 << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2603 ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2604 } else {
2605 SourceLocation LAngleLoc =
2606 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2608 diag::err_explicit_instantiation_with_definition)
2609 << SourceRange(TemplateInfo.TemplateLoc)
2610 << FixItHint::CreateInsertion(LAngleLoc, "<>");
2611
2612 // Recover as if it were an explicit specialization.
2613 TemplateParameterLists FakedParamLists;
2614 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2615 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, {},
2616 LAngleLoc, nullptr));
2617
2618 ThisDecl =
2619 Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2620 }
2621 }
2622 break;
2623 }
2624 }
2625
2626 SemaCUDA::CUDATargetContextRAII X(Actions.CUDA(),
2628 switch (TheInitKind) {
2629 // Parse declarator '=' initializer.
2630 case InitKind::Equal: {
2631 SourceLocation EqualLoc = ConsumeToken();
2632
2633 if (Tok.is(tok::kw_delete)) {
2634 if (D.isFunctionDeclarator())
2635 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2636 << 1 /* delete */;
2637 else
2638 Diag(ConsumeToken(), diag::err_deleted_non_function);
2639 SkipDeletedFunctionBody();
2640 } else if (Tok.is(tok::kw_default)) {
2641 if (D.isFunctionDeclarator())
2642 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2643 << 0 /* default */;
2644 else
2645 Diag(ConsumeToken(), diag::err_default_special_members)
2646 << getLangOpts().CPlusPlus20;
2647 } else {
2648 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2649
2650 if (Tok.is(tok::code_completion)) {
2651 cutOffParsing();
2652 Actions.CodeCompletion().CodeCompleteInitializer(getCurScope(),
2653 ThisDecl);
2654 Actions.FinalizeDeclaration(ThisDecl);
2655 return nullptr;
2656 }
2657
2658 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2659 ExprResult Init = ParseInitializer(ThisDecl);
2660
2661 // If this is the only decl in (possibly) range based for statement,
2662 // our best guess is that the user meant ':' instead of '='.
2663 if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2664 Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2665 << FixItHint::CreateReplacement(EqualLoc, ":");
2666 // We are trying to stop parser from looking for ';' in this for
2667 // statement, therefore preventing spurious errors to be issued.
2668 FRI->ColonLoc = EqualLoc;
2669 Init = ExprError();
2670 FRI->RangeExpr = Init;
2671 }
2672
2673 if (Init.isInvalid()) {
2675 StopTokens.push_back(tok::comma);
2678 StopTokens.push_back(tok::r_paren);
2679 SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2680 Actions.ActOnInitializerError(ThisDecl);
2681 } else
2682 Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2683 /*DirectInit=*/false);
2684 }
2685 break;
2686 }
2687 case InitKind::CXXDirect: {
2688 // Parse C++ direct initializer: '(' expression-list ')'
2689 BalancedDelimiterTracker T(*this, tok::l_paren);
2690 T.consumeOpen();
2691
2692 ExprVector Exprs;
2693
2694 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2695
2696 auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2697 auto RunSignatureHelp = [&]() {
2698 QualType PreferredType =
2699 Actions.CodeCompletion().ProduceConstructorSignatureHelp(
2700 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2701 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2702 /*Braced=*/false);
2703 CalledSignatureHelp = true;
2704 return PreferredType;
2705 };
2706 auto SetPreferredType = [&] {
2707 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2708 };
2709
2710 llvm::function_ref<void()> ExpressionStarts;
2711 if (ThisVarDecl) {
2712 // ParseExpressionList can sometimes succeed even when ThisDecl is not
2713 // VarDecl. This is an error and it is reported in a call to
2714 // Actions.ActOnInitializerError(). However, we call
2715 // ProduceConstructorSignatureHelp only on VarDecls.
2716 ExpressionStarts = SetPreferredType;
2717 }
2718
2719 bool SawError = ParseExpressionList(Exprs, ExpressionStarts);
2720
2721 if (SawError) {
2722 if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2723 Actions.CodeCompletion().ProduceConstructorSignatureHelp(
2724 ThisVarDecl->getType()->getCanonicalTypeInternal(),
2725 ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2726 /*Braced=*/false);
2727 CalledSignatureHelp = true;
2728 }
2729 Actions.ActOnInitializerError(ThisDecl);
2730 SkipUntil(tok::r_paren, StopAtSemi);
2731 } else {
2732 // Match the ')'.
2733 T.consumeClose();
2734
2735 ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2736 T.getCloseLocation(),
2737 Exprs);
2738 Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2739 /*DirectInit=*/true);
2740 }
2741 break;
2742 }
2743 case InitKind::CXXBraced: {
2744 // Parse C++0x braced-init-list.
2745 Diag(Tok, diag::compat_cxx11_generalized_initializer_lists);
2746
2747 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2748
2749 PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2750 ExprResult Init(ParseBraceInitializer());
2751
2752 if (Init.isInvalid()) {
2753 Actions.ActOnInitializerError(ThisDecl);
2754 } else
2755 Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2756 break;
2757 }
2758 case InitKind::Uninitialized: {
2759 InitializerScopeRAII InitScope(*this, D, ThisDecl);
2760 Actions.ActOnUninitializedDecl(ThisDecl);
2761 break;
2762 }
2763 }
2764
2765 Actions.FinalizeDeclaration(ThisDecl);
2766 return OuterDecl ? OuterDecl : ThisDecl;
2767}
2768
2769void Parser::ParseSpecifierQualifierList(
2770 DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2771 AccessSpecifier AS, DeclSpecContext DSC, LateParsedAttrList *LateAttrs) {
2772 ParsedTemplateInfo TemplateInfo;
2773
2774 assert((!LateAttrs ||
2775 llvm::none_of(*LateAttrs, llvm::IsaPred<LateParsedTypeAttribute>)) &&
2776 "caller's late-attribute list must not hold type attributes yet");
2777
2778 /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2779 /// parse declaration-specifiers and complain about extra stuff.
2780 /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2781 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC, LateAttrs,
2782 AllowImplicitTypename);
2783
2784 // Validate declspec for type-name.
2785 unsigned Specs = DS.getParsedSpecifiers();
2786 if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2787 Diag(Tok, diag::err_expected_type);
2788 DS.SetTypeSpecError();
2789 } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2790 Diag(Tok, diag::err_typename_requires_specqual);
2791 if (!DS.hasTypeSpecifier())
2792 DS.SetTypeSpecError();
2793 }
2794
2795 // Issue diagnostic and remove storage class if present.
2798 Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2799 else
2801 diag::err_typename_invalid_storageclass);
2803 }
2804
2805 // Issue diagnostic and remove function specifier if present.
2806 if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2807 if (DS.isInlineSpecified())
2808 Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2809 if (DS.isVirtualSpecified())
2810 Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2811 if (DS.hasExplicitSpecifier())
2812 Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2813 if (DS.isNoreturnSpecified())
2814 Diag(DS.getNoreturnSpecLoc(), diag::err_typename_invalid_functionspec);
2815 DS.ClearFunctionSpecs();
2816 }
2817
2818 // Issue diagnostic and remove constexpr specifier if present.
2819 if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2820 Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2821 << static_cast<int>(DS.getConstexprSpecifier());
2822 DS.ClearConstexprSpec();
2823 }
2824}
2825
2826/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2827/// specified token is valid after the identifier in a declarator which
2828/// immediately follows the declspec. For example, these things are valid:
2829///
2830/// int x [ 4]; // direct-declarator
2831/// int x ( int y); // direct-declarator
2832/// int(int x ) // direct-declarator
2833/// int x ; // simple-declaration
2834/// int x = 17; // init-declarator-list
2835/// int x , y; // init-declarator-list
2836/// int x __asm__ ("foo"); // init-declarator-list
2837/// int x : 4; // struct-declarator
2838/// int x { 5}; // C++'0x unified initializers
2839///
2840/// This is not, because 'x' does not immediately follow the declspec (though
2841/// ')' happens to be valid anyway).
2842/// int (x)
2843///
2845 return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2846 tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2847 tok::colon);
2848}
2849
2850bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2851 ParsedTemplateInfo &TemplateInfo,
2852 AccessSpecifier AS, DeclSpecContext DSC,
2853 ParsedAttributes &Attrs) {
2854 assert(Tok.is(tok::identifier) && "should have identifier");
2855
2856 SourceLocation Loc = Tok.getLocation();
2857 // If we see an identifier that is not a type name, we normally would
2858 // parse it as the identifier being declared. However, when a typename
2859 // is typo'd or the definition is not included, this will incorrectly
2860 // parse the typename as the identifier name and fall over misparsing
2861 // later parts of the diagnostic.
2862 //
2863 // As such, we try to do some look-ahead in cases where this would
2864 // otherwise be an "implicit-int" case to see if this is invalid. For
2865 // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2866 // an identifier with implicit int, we'd get a parse error because the
2867 // next token is obviously invalid for a type. Parse these as a case
2868 // with an invalid type specifier.
2869 assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2870
2871 // Since we know that this either implicit int (which is rare) or an
2872 // error, do lookahead to try to do better recovery. This never applies
2873 // within a type specifier. Outside of C++, we allow this even if the
2874 // language doesn't "officially" support implicit int -- we support
2875 // implicit int as an extension in some language modes.
2876 if (!isTypeSpecifier(DSC) && getLangOpts().isImplicitIntAllowed() &&
2878 // If this token is valid for implicit int, e.g. "static x = 4", then
2879 // we just avoid eating the identifier, so it will be parsed as the
2880 // identifier in the declarator.
2881 return false;
2882 }
2883
2884 // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2885 // for incomplete declarations such as `pipe p`.
2886 if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2887 return false;
2888
2889 if (getLangOpts().CPlusPlus &&
2891 // Don't require a type specifier if we have the 'auto' storage class
2892 // specifier in C++98 -- we'll promote it to a type specifier.
2893 if (SS)
2894 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2895 return false;
2896 }
2897
2898 if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2899 getLangOpts().MSVCCompat) {
2900 // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2901 // Give Sema a chance to recover if we are in a template with dependent base
2902 // classes.
2903 if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2904 *Tok.getIdentifierInfo(), Tok.getLocation(),
2905 DSC == DeclSpecContext::DSC_template_type_arg)) {
2906 const char *PrevSpec;
2907 unsigned DiagID;
2908 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2909 Actions.getASTContext().getPrintingPolicy());
2910 DS.SetRangeEnd(Tok.getLocation());
2911 ConsumeToken();
2912 return false;
2913 }
2914 }
2915
2916 // Otherwise, if we don't consume this token, we are going to emit an
2917 // error anyway. Try to recover from various common problems. Check
2918 // to see if this was a reference to a tag name without a tag specified.
2919 // This is a common problem in C (saying 'foo' instead of 'struct foo').
2920 //
2921 // C++ doesn't need this, and isTagName doesn't take SS.
2922 if (SS == nullptr) {
2923 const char *TagName = nullptr, *FixitTagName = nullptr;
2924 tok::TokenKind TagKind = tok::unknown;
2925
2926 switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2927 default: break;
2928 case DeclSpec::TST_enum:
2929 TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2931 TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2933 TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2935 TagName="__interface"; FixitTagName = "__interface ";
2936 TagKind=tok::kw___interface;break;
2938 TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2939 }
2940
2941 if (TagName) {
2942 IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2943 LookupResult R(Actions, TokenName, SourceLocation(),
2945
2946 Diag(Loc, diag::err_use_of_tag_name_without_tag)
2947 << TokenName << TagName << getLangOpts().CPlusPlus
2948 << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2949
2950 if (Actions.LookupName(R, getCurScope())) {
2951 for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2952 I != IEnd; ++I)
2953 Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2954 << TokenName << TagName;
2955 }
2956
2957 // Parse this as a tag as if the missing tag were present.
2958 if (TagKind == tok::kw_enum)
2959 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2960 DeclSpecContext::DSC_normal);
2961 else
2962 ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2963 /*EnteringContext*/ false,
2964 DeclSpecContext::DSC_normal, Attrs);
2965 return true;
2966 }
2967 }
2968
2969 // Determine whether this identifier could plausibly be the name of something
2970 // being declared (with a missing type).
2971 if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2972 DSC == DeclSpecContext::DSC_class)) {
2973 // Look ahead to the next token to try to figure out what this declaration
2974 // was supposed to be.
2975 switch (NextToken().getKind()) {
2976 case tok::l_paren: {
2977 // static x(4); // 'x' is not a type
2978 // x(int n); // 'x' is not a type
2979 // x (*p)[]; // 'x' is a type
2980 //
2981 // Since we're in an error case, we can afford to perform a tentative
2982 // parse to determine which case we're in.
2983 TentativeParsingAction PA(*this);
2984 ConsumeToken();
2985 TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2986 PA.Revert();
2987
2988 if (TPR != TPResult::False) {
2989 // The identifier is followed by a parenthesized declarator.
2990 // It's supposed to be a type.
2991 break;
2992 }
2993
2994 // If we're in a context where we could be declaring a constructor,
2995 // check whether this is a constructor declaration with a bogus name.
2996 if (DSC == DeclSpecContext::DSC_class ||
2997 (DSC == DeclSpecContext::DSC_top_level && SS)) {
2998 IdentifierInfo *II = Tok.getIdentifierInfo();
2999 if (Actions.isCurrentClassNameTypo(II, SS)) {
3000 Diag(Loc, diag::err_constructor_bad_name)
3001 << Tok.getIdentifierInfo() << II
3002 << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
3003 Tok.setIdentifierInfo(II);
3004 }
3005 }
3006 // Fall through.
3007 [[fallthrough]];
3008 }
3009 case tok::comma:
3010 case tok::equal:
3011 case tok::kw_asm:
3012 case tok::l_brace:
3013 case tok::l_square:
3014 case tok::semi:
3015 // This looks like a variable or function declaration. The type is
3016 // probably missing. We're done parsing decl-specifiers.
3017 // But only if we are not in a function prototype scope.
3018 if (getCurScope()->isFunctionPrototypeScope())
3019 break;
3020 if (SS)
3021 AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
3022 return false;
3023
3024 default:
3025 // This is probably supposed to be a type. This includes cases like:
3026 // int f(itn);
3027 // struct S { unsigned : 4; };
3028 break;
3029 }
3030 }
3031
3032 // This is almost certainly an invalid type name. Let Sema emit a diagnostic
3033 // and attempt to recover.
3034 ParsedType T;
3035 IdentifierInfo *II = Tok.getIdentifierInfo();
3036 bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
3037 Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
3038 IsTemplateName);
3039 if (T) {
3040 // The action has suggested that the type T could be used. Set that as
3041 // the type in the declaration specifiers, consume the would-be type
3042 // name token, and we're done.
3043 const char *PrevSpec;
3044 unsigned DiagID;
3045 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
3046 Actions.getASTContext().getPrintingPolicy());
3047 DS.SetRangeEnd(Tok.getLocation());
3048 ConsumeToken();
3049 // There may be other declaration specifiers after this.
3050 return true;
3051 } else if (II != Tok.getIdentifierInfo()) {
3052 // If no type was suggested, the correction is to a keyword
3053 Tok.setKind(II->getTokenID());
3054 // There may be other declaration specifiers after this.
3055 return true;
3056 }
3057
3058 // Otherwise, the action had no suggestion for us. Mark this as an error.
3059 DS.SetTypeSpecError();
3060 DS.SetRangeEnd(Tok.getLocation());
3061 ConsumeToken();
3062
3063 // Eat any following template arguments.
3064 if (IsTemplateName) {
3065 SourceLocation LAngle, RAngle;
3066 TemplateArgList Args;
3067 ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
3068 }
3069
3070 // TODO: Could inject an invalid typedef decl in an enclosing scope to
3071 // avoid rippling error messages on subsequent uses of the same type,
3072 // could be useful if #include was forgotten.
3073 return true;
3074}
3075
3076Parser::DeclSpecContext
3077Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
3078 switch (Context) {
3080 return DeclSpecContext::DSC_class;
3082 return DeclSpecContext::DSC_top_level;
3084 return DeclSpecContext::DSC_template_param;
3086 return DeclSpecContext::DSC_template_arg;
3088 return DeclSpecContext::DSC_template_type_arg;
3091 return DeclSpecContext::DSC_trailing;
3094 return DeclSpecContext::DSC_alias_declaration;
3096 return DeclSpecContext::DSC_association;
3098 return DeclSpecContext::DSC_type_specifier;
3100 return DeclSpecContext::DSC_condition;
3102 return DeclSpecContext::DSC_conv_operator;
3104 return DeclSpecContext::DSC_new;
3119 return DeclSpecContext::DSC_normal;
3120 }
3121
3122 llvm_unreachable("Missing DeclaratorContext case");
3123}
3124
3125ExprResult Parser::ParseAlignArgument(StringRef KWName, SourceLocation Start,
3126 SourceLocation &EllipsisLoc, bool &IsType,
3128 ExprResult ER;
3129 if (isTypeIdInParens()) {
3130 SourceLocation TypeLoc = Tok.getLocation();
3131 ParsedType Ty = ParseTypeName().get();
3132 SourceRange TypeRange(Start, Tok.getLocation());
3133 if (Actions.ActOnAlignasTypeArgument(KWName, Ty, TypeLoc, TypeRange))
3134 return ExprError();
3135 TypeResult = Ty;
3136 IsType = true;
3137 } else {
3139 IsType = false;
3140 }
3141
3143 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3144
3145 return ER;
3146}
3147
3148void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
3149 SourceLocation *EndLoc) {
3150 assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
3151 "Not an alignment-specifier!");
3152 Token KWTok = Tok;
3153 IdentifierInfo *KWName = KWTok.getIdentifierInfo();
3154 auto Kind = KWTok.getKind();
3155 SourceLocation KWLoc = ConsumeToken();
3156
3157 BalancedDelimiterTracker T(*this, tok::l_paren);
3158 if (T.expectAndConsume())
3159 return;
3160
3161 bool IsType;
3163 SourceLocation EllipsisLoc;
3164 ExprResult ArgExpr =
3165 ParseAlignArgument(PP.getSpelling(KWTok), T.getOpenLocation(),
3166 EllipsisLoc, IsType, TypeResult);
3167 if (ArgExpr.isInvalid()) {
3168 T.skipToEnd();
3169 return;
3170 }
3171
3172 T.consumeClose();
3173 if (EndLoc)
3174 *EndLoc = T.getCloseLocation();
3175
3176 if (IsType) {
3177 Attrs.addNewTypeAttr(KWName, KWLoc, AttributeScopeInfo(), TypeResult, Kind,
3178 EllipsisLoc);
3179 } else {
3180 ArgsVector ArgExprs;
3181 ArgExprs.push_back(ArgExpr.get());
3182 Attrs.addNew(KWName, KWLoc, AttributeScopeInfo(), ArgExprs.data(), 1, Kind,
3183 EllipsisLoc);
3184 }
3185}
3186
3187void Parser::DistributeCLateParsedAttrs(Decl *Dcl,
3188 LateParsedAttrList *LateAttrs) {
3189 if (!LateAttrs)
3190 return;
3191
3192 if (Dcl) {
3193 for (auto *LateAttr : *LateAttrs) {
3194 if (LateAttr->Decls.empty())
3195 LateAttr->addDecl(Dcl);
3196 }
3197 }
3198}
3199
3200void Parser::ParsePtrauthQualifier(ParsedAttributes &Attrs) {
3201 assert(Tok.is(tok::kw___ptrauth));
3202
3203 IdentifierInfo *KwName = Tok.getIdentifierInfo();
3204 SourceLocation KwLoc = ConsumeToken();
3205
3206 BalancedDelimiterTracker T(*this, tok::l_paren);
3207 if (T.expectAndConsume())
3208 return;
3209
3210 ArgsVector ArgExprs;
3211 do {
3213 if (ER.isInvalid()) {
3214 T.skipToEnd();
3215 return;
3216 }
3217 ArgExprs.push_back(ER.get());
3218 } while (TryConsumeToken(tok::comma));
3219
3220 T.consumeClose();
3221 SourceLocation EndLoc = T.getCloseLocation();
3222
3223 if (ArgExprs.empty() || ArgExprs.size() > 3) {
3224 Diag(KwLoc, diag::err_ptrauth_qualifier_bad_arg_count);
3225 return;
3226 }
3227
3228 Attrs.addNew(KwName, SourceRange(KwLoc, EndLoc), AttributeScopeInfo(),
3229 ArgExprs.data(), ArgExprs.size(),
3230 ParsedAttr::Form::Keyword(/*IsAlignAs=*/false,
3231 /*IsRegularKeywordAttribute=*/false));
3232}
3233
3234void Parser::ParseBoundsAttribute(IdentifierInfo &AttrName,
3235 SourceLocation AttrNameLoc,
3236 ParsedAttributes &Attrs,
3237 IdentifierInfo *ScopeName,
3238 SourceLocation ScopeLoc,
3239 ParsedAttr::Form Form) {
3240 assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
3241
3242 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3243 Parens.consumeOpen();
3244
3245 if (Tok.is(tok::r_paren)) {
3246 Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
3247 Parens.consumeClose();
3248 return;
3249 }
3250
3251 ArgsVector ArgExprs;
3252 // Don't evaluate argument when the attribute is ignored.
3253 using ExpressionKind =
3255 EnterExpressionEvaluationContext EC(
3257 ExpressionKind::EK_AttrArgument);
3258
3260 if (ArgExpr.isInvalid()) {
3261 Parens.skipToEnd();
3262 return;
3263 }
3264
3265 ArgExprs.push_back(ArgExpr.get());
3266 Parens.consumeClose();
3267
3268 ASTContext &Ctx = Actions.getASTContext();
3269
3270 ArgExprs.push_back(IntegerLiteral::Create(
3271 Ctx, llvm::APInt(Ctx.getTypeSize(Ctx.getSizeType()), 0),
3272 Ctx.getSizeType(), SourceLocation()));
3273
3274 Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
3275 AttributeScopeInfo(), ArgExprs.data(), ArgExprs.size(), Form);
3276}
3277
3278ExprResult Parser::ParseExtIntegerArgument() {
3279 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
3280 "Not an extended int type");
3281 ConsumeToken();
3282
3283 BalancedDelimiterTracker T(*this, tok::l_paren);
3284 if (T.expectAndConsume())
3285 return ExprError();
3286
3288 if (ER.isInvalid()) {
3289 T.skipToEnd();
3290 return ExprError();
3291 }
3292
3293 if(T.consumeClose())
3294 return ExprError();
3295 return ER;
3296}
3297
3298bool
3299Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
3300 DeclSpecContext DSContext,
3301 LateParsedAttrList *LateAttrs) {
3302 assert(DS.hasTagDefinition() && "shouldn't call this");
3303
3304 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3305 DSContext == DeclSpecContext::DSC_top_level);
3306
3307 if (getLangOpts().CPlusPlus &&
3308 (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype) ||
3309 (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon))) &&
3310 TryAnnotateCXXScopeToken(EnteringContext)) {
3312 return true;
3313 }
3314
3315 bool HasScope = Tok.is(tok::annot_cxxscope);
3316 // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
3317 Token AfterScope = HasScope ? NextToken() : Tok;
3318
3319 // Determine whether the following tokens could possibly be a
3320 // declarator.
3321 bool MightBeDeclarator = true;
3322 if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
3323 // A declarator-id can't start with 'typename'.
3324 MightBeDeclarator = false;
3325 } else if (AfterScope.is(tok::annot_template_id)) {
3326 // If we have a type expressed as a template-id, this cannot be a
3327 // declarator-id (such a type cannot be redeclared in a simple-declaration).
3328 TemplateIdAnnotation *Annot =
3329 static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
3330 if (Annot->Kind == TNK_Type_template)
3331 MightBeDeclarator = false;
3332 } else if (AfterScope.is(tok::identifier)) {
3333 const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
3334
3335 // These tokens cannot come after the declarator-id in a
3336 // simple-declaration, and are likely to come after a type-specifier.
3337 if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
3338 tok::annot_cxxscope, tok::coloncolon)) {
3339 // Missing a semicolon.
3340 MightBeDeclarator = false;
3341 } else if (HasScope) {
3342 // If the declarator-id has a scope specifier, it must redeclare a
3343 // previously-declared entity. If that's a type (and this is not a
3344 // typedef), that's an error.
3345 CXXScopeSpec SS;
3346 Actions.RestoreNestedNameSpecifierAnnotation(
3347 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3348 IdentifierInfo *Name = AfterScope.getIdentifierInfo();
3349 Sema::NameClassification Classification = Actions.ClassifyName(
3350 getCurScope(), SS, Name, AfterScope.getLocation(), Next,
3351 /*CCC=*/nullptr);
3352 switch (Classification.getKind()) {
3355 return true;
3356
3358 llvm_unreachable("typo correction is not possible here");
3359
3365 // Not a previously-declared non-type entity.
3366 MightBeDeclarator = false;
3367 break;
3368
3375 // Might be a redeclaration of a prior entity.
3376 break;
3377 }
3378 }
3379 }
3380
3381 if (MightBeDeclarator)
3382 return false;
3383
3384 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
3385 Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
3386 diag::err_expected_after)
3387 << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
3388
3389 // Try to recover from the typo, by dropping the tag definition and parsing
3390 // the problematic tokens as a type.
3391 //
3392 // FIXME: Split the DeclSpec into pieces for the standalone
3393 // declaration and pieces for the following declaration, instead
3394 // of assuming that all the other pieces attach to new declaration,
3395 // and call ParsedFreeStandingDeclSpec as appropriate.
3396 DS.ClearTypeSpecType();
3397 ParsedTemplateInfo NotATemplate;
3398 ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
3399 return false;
3400}
3401
3402void Parser::ParseDeclarationSpecifiers(
3403 DeclSpec &DS, ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
3404 DeclSpecContext DSContext, LateParsedAttrList *LateAttrs,
3405 ImplicitTypenameContext AllowImplicitTypename) {
3406 if (DS.getSourceRange().isInvalid()) {
3407 // Start the range at the current token but make the end of the range
3408 // invalid. This will make the entire range invalid unless we successfully
3409 // consume a token.
3410 DS.SetRangeStart(Tok.getLocation());
3411 DS.SetRangeEnd(SourceLocation());
3412 }
3413
3414 // If we are in a operator context, convert it back into a type specifier
3415 // context for better error handling later on.
3416 if (DSContext == DeclSpecContext::DSC_conv_operator)
3417 DSContext = DeclSpecContext::DSC_type_specifier;
3418
3419 bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3420 DSContext == DeclSpecContext::DSC_top_level);
3421 bool AttrsLastTime = false;
3422 ParsedAttributes attrs(AttrFactory);
3423 // We use Sema's policy to get bool macros right.
3424 PrintingPolicy Policy = Actions.getPrintingPolicy();
3425 while (true) {
3426 bool isInvalid = false;
3427 bool isStorageClass = false;
3428 const char *PrevSpec = nullptr;
3429 unsigned DiagID = 0;
3430
3431 // This value needs to be set to the location of the last token if the last
3432 // token of the specifier is already consumed.
3433 SourceLocation ConsumedEnd;
3434
3435 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3436 // implementation for VS2013 uses _Atomic as an identifier for one of the
3437 // classes in <atomic>.
3438 //
3439 // A typedef declaration containing _Atomic<...> is among the places where
3440 // the class is used. If we are currently parsing such a declaration, treat
3441 // the token as an identifier.
3442 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3444 !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3445 Tok.setKind(tok::identifier);
3446
3447 SourceLocation Loc = Tok.getLocation();
3448
3449 // Helper for image types in OpenCL.
3450 auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
3451 // Check if the image type is supported and otherwise turn the keyword into an identifier
3452 // because image types from extensions are not reserved identifiers.
3453 if (!StringRef(Ext).empty() && !getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())) {
3454 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3455 Tok.setKind(tok::identifier);
3456 return false;
3457 }
3458 isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3459 return true;
3460 };
3461
3462 // Turn off usual access checking for template specializations and
3463 // instantiations.
3464 bool IsTemplateSpecOrInst =
3465 (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation ||
3466 TemplateInfo.Kind == ParsedTemplateKind::ExplicitSpecialization);
3467
3468 switch (Tok.getKind()) {
3469 default:
3470 if (Tok.isRegularKeywordAttribute())
3471 goto Attribute;
3472
3473 DoneWithDeclSpec:
3474 if (!AttrsLastTime)
3475 ProhibitAttributes(attrs);
3476 else {
3477 // Reject C++11 / C23 attributes that aren't type attributes.
3478 for (const ParsedAttr &PA : attrs) {
3479 if (!PA.isCXX11Attribute() && !PA.isC23Attribute() &&
3480 !PA.isRegularKeywordAttribute())
3481 continue;
3482 if (PA.getKind() == ParsedAttr::UnknownAttribute)
3483 // We will warn about the unknown attribute elsewhere (in
3484 // SemaDeclAttr.cpp)
3485 continue;
3486 // GCC ignores this attribute when placed on the DeclSpec in [[]]
3487 // syntax, so we do the same.
3488 if (PA.getKind() == ParsedAttr::AT_VectorSize) {
3489 Diag(PA.getLoc(), diag::warn_attribute_ignored) << PA;
3490 PA.setInvalid();
3491 continue;
3492 }
3493 // We reject AT_LifetimeBound and AT_AnyX86NoCfCheck, even though they
3494 // are type attributes, because we historically haven't allowed these
3495 // to be used as type attributes in C++11 / C23 syntax.
3496 if (PA.isTypeAttr() && PA.getKind() != ParsedAttr::AT_LifetimeBound &&
3497 PA.getKind() != ParsedAttr::AT_AnyX86NoCfCheck)
3498 continue;
3499
3500 if (PA.getKind() == ParsedAttr::AT_LifetimeBound)
3501 Diag(PA.getLoc(), diag::err_attribute_wrong_decl_type)
3502 << PA << PA.isRegularKeywordAttribute()
3504 else
3505 Diag(PA.getLoc(), diag::err_attribute_not_type_attr)
3506 << PA << PA.isRegularKeywordAttribute();
3507 PA.setInvalid();
3508 }
3509
3511 }
3512
3513 // If this is not a declaration specifier token, we're done reading decl
3514 // specifiers. First verify that DeclSpec's are consistent.
3515 DS.Finish(Actions, Policy);
3516 return;
3517
3518 // alignment-specifier
3519 case tok::kw__Alignas:
3520 diagnoseUseOfC11Keyword(Tok);
3521 [[fallthrough]];
3522 case tok::kw_alignas:
3523 // _Alignas and alignas (C23, not C++) should parse the same way. The C++
3524 // parsing for alignas happens through the usual attribute parsing. This
3525 // ensures that an alignas specifier can appear in a type position in C
3526 // despite that not being valid in C++.
3527 if (getLangOpts().C23 || Tok.getKind() == tok::kw__Alignas) {
3528 if (Tok.getKind() == tok::kw_alignas)
3529 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
3530 ParseAlignmentSpecifier(DS.getAttributes());
3531 continue;
3532 }
3533 [[fallthrough]];
3534 case tok::l_square:
3535 if (!isAllowedCXX11AttributeSpecifier())
3536 goto DoneWithDeclSpec;
3537
3538 Attribute:
3539 ProhibitAttributes(attrs);
3540 // FIXME: It would be good to recover by accepting the attributes,
3541 // but attempting to do that now would cause serious
3542 // madness in terms of diagnostics.
3543 attrs.clear();
3544 attrs.Range = SourceRange();
3545
3546 ParseCXX11Attributes(attrs);
3547 AttrsLastTime = true;
3548 continue;
3549
3550 case tok::code_completion: {
3553 if (DS.hasTypeSpecifier()) {
3554 bool AllowNonIdentifiers
3559 Scope::AtCatchScope)) == 0;
3560 bool AllowNestedNameSpecifiers
3561 = DSContext == DeclSpecContext::DSC_top_level ||
3562 (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3563
3564 cutOffParsing();
3565 Actions.CodeCompletion().CodeCompleteDeclSpec(
3566 getCurScope(), DS, AllowNonIdentifiers, AllowNestedNameSpecifiers);
3567 return;
3568 }
3569
3570 // Class context can appear inside a function/block, so prioritise that.
3571 if (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate)
3572 CCC = DSContext == DeclSpecContext::DSC_class
3575 else if (DSContext == DeclSpecContext::DSC_class)
3577 else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3579 else if (CurParsedObjCImpl)
3581
3582 cutOffParsing();
3583 Actions.CodeCompletion().CodeCompleteOrdinaryName(getCurScope(), CCC);
3584 return;
3585 }
3586
3587 case tok::coloncolon: // ::foo::bar
3588 // C++ scope specifier. Annotate and loop, or bail out on error.
3589 if (getLangOpts().CPlusPlus &&
3590 TryAnnotateCXXScopeToken(EnteringContext)) {
3591 if (!DS.hasTypeSpecifier())
3592 DS.SetTypeSpecError();
3593 goto DoneWithDeclSpec;
3594 }
3595 if (Tok.is(tok::coloncolon)) // ::new or ::delete
3596 goto DoneWithDeclSpec;
3597 continue;
3598
3599 case tok::annot_cxxscope: {
3600 if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3601 goto DoneWithDeclSpec;
3602
3603 CXXScopeSpec SS;
3604 if (TemplateInfo.TemplateParams)
3605 SS.setTemplateParamLists(*TemplateInfo.TemplateParams);
3606 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3607 Tok.getAnnotationRange(),
3608 SS);
3609
3610 // We are looking for a qualified typename.
3611 Token Next = NextToken();
3612
3613 TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3614 ? takeTemplateIdAnnotation(Next)
3615 : nullptr;
3616 if (TemplateId && TemplateId->hasInvalidName()) {
3617 // We found something like 'T::U<Args> x', but U is not a template.
3618 // Assume it was supposed to be a type.
3619 DS.SetTypeSpecError();
3620 ConsumeAnnotationToken();
3621 break;
3622 }
3623
3624 if (TemplateId && TemplateId->Kind == TNK_Type_template) {
3625 // We have a qualified template-id, e.g., N::A<int>
3626
3627 // If this would be a valid constructor declaration with template
3628 // arguments, we will reject the attempt to form an invalid type-id
3629 // referring to the injected-class-name when we annotate the token,
3630 // per C++ [class.qual]p2.
3631 //
3632 // To improve diagnostics for this case, parse the declaration as a
3633 // constructor (and reject the extra template arguments later).
3634 if ((DSContext == DeclSpecContext::DSC_top_level ||
3635 DSContext == DeclSpecContext::DSC_class) &&
3636 TemplateId->Name &&
3637 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3638 isConstructorDeclarator(/*Unqualified=*/false,
3639 /*DeductionGuide=*/false,
3640 DS.isFriendSpecified())) {
3641 // The user meant this to be an out-of-line constructor
3642 // definition, but template arguments are not allowed
3643 // there. Just allow this as a constructor; we'll
3644 // complain about it later.
3645 goto DoneWithDeclSpec;
3646 }
3647
3648 DS.getTypeSpecScope() = SS;
3649 ConsumeAnnotationToken(); // The C++ scope.
3650 assert(Tok.is(tok::annot_template_id) &&
3651 "ParseOptionalCXXScopeSpecifier not working");
3652 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3653 continue;
3654 }
3655
3656 if (TemplateId && TemplateId->Kind == TNK_Concept_template) {
3657 DS.getTypeSpecScope() = SS;
3658 // This is probably a qualified placeholder-specifier, e.g., ::C<int>
3659 // auto ... Consume the scope annotation and continue to consume the
3660 // template-id as a placeholder-specifier. Let the next iteration
3661 // diagnose a missing auto.
3662 ConsumeAnnotationToken();
3663 continue;
3664 }
3665
3666 if (Next.is(tok::annot_typename)) {
3667 DS.getTypeSpecScope() = SS;
3668 ConsumeAnnotationToken(); // The C++ scope.
3671 Tok.getAnnotationEndLoc(),
3672 PrevSpec, DiagID, T, Policy);
3673 if (isInvalid)
3674 break;
3675 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3676 ConsumeAnnotationToken(); // The typename
3677 }
3678
3679 if (AllowImplicitTypename == ImplicitTypenameContext::Yes &&
3680 Next.is(tok::annot_template_id) &&
3681 static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3682 ->Kind == TNK_Dependent_template_name) {
3683 DS.getTypeSpecScope() = SS;
3684 ConsumeAnnotationToken(); // The C++ scope.
3685 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3686 continue;
3687 }
3688
3689 if (Next.isNot(tok::identifier))
3690 goto DoneWithDeclSpec;
3691
3692 // Check whether this is a constructor declaration. If we're in a
3693 // context where the identifier could be a class name, and it has the
3694 // shape of a constructor declaration, process it as one.
3695 if ((DSContext == DeclSpecContext::DSC_top_level ||
3696 DSContext == DeclSpecContext::DSC_class) &&
3697 Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3698 &SS) &&
3699 isConstructorDeclarator(/*Unqualified=*/false,
3700 /*DeductionGuide=*/false,
3701 DS.isFriendSpecified(),
3702 &TemplateInfo))
3703 goto DoneWithDeclSpec;
3704
3705 // C++20 [temp.spec] 13.9/6.
3706 // This disables the access checking rules for function template explicit
3707 // instantiation and explicit specialization:
3708 // - `return type`.
3709 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3710
3711 ParsedType TypeRep = Actions.getTypeName(
3712 *Next.getIdentifierInfo(), Next.getLocation(), getCurScope(), &SS,
3713 false, false, nullptr,
3714 /*IsCtorOrDtorName=*/false,
3715 /*WantNontrivialTypeSourceInfo=*/true,
3716 isClassTemplateDeductionContext(DSContext), AllowImplicitTypename);
3717
3718 if (IsTemplateSpecOrInst)
3719 SAC.done();
3720
3721 // If the referenced identifier is not a type, then this declspec is
3722 // erroneous: We already checked about that it has no type specifier, and
3723 // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3724 // typename.
3725 if (!TypeRep) {
3726 if (TryAnnotateTypeConstraint())
3727 goto DoneWithDeclSpec;
3728 if (Tok.isNot(tok::annot_cxxscope) ||
3729 NextToken().isNot(tok::identifier))
3730 continue;
3731 // Eat the scope spec so the identifier is current.
3732 ConsumeAnnotationToken();
3733 ParsedAttributes Attrs(AttrFactory);
3734 if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3735 if (!Attrs.empty()) {
3736 AttrsLastTime = true;
3737 attrs.takeAllAppendingFrom(Attrs);
3738 }
3739 continue;
3740 }
3741 goto DoneWithDeclSpec;
3742 }
3743
3744 DS.getTypeSpecScope() = SS;
3745 ConsumeAnnotationToken(); // The C++ scope.
3746
3748 DiagID, TypeRep, Policy);
3749 if (isInvalid)
3750 break;
3751
3752 DS.SetRangeEnd(Tok.getLocation());
3753 ConsumeToken(); // The typename.
3754
3755 continue;
3756 }
3757
3758 case tok::annot_typename: {
3759 // If we've previously seen a tag definition, we were almost surely
3760 // missing a semicolon after it.
3761 if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3762 goto DoneWithDeclSpec;
3763
3766 DiagID, T, Policy);
3767 if (isInvalid)
3768 break;
3769
3770 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3771 ConsumeAnnotationToken(); // The typename
3772
3773 continue;
3774 }
3775
3776 case tok::kw___is_signed:
3777 // HACK: before 2022-12, libstdc++ uses __is_signed as an identifier,
3778 // but Clang typically treats it as a trait.
3779 // If we see __is_signed as it appears in libstdc++, e.g.,
3780 //
3781 // static const bool __is_signed;
3782 //
3783 // then treat __is_signed as an identifier rather than as a keyword.
3784 // This was fixed by libstdc++ in December 2022.
3785 if (DS.getTypeSpecType() == TST_bool &&
3788 TryKeywordIdentFallback(true);
3789
3790 // We're done with the declaration-specifiers.
3791 goto DoneWithDeclSpec;
3792
3793 // typedef-name
3794 case tok::kw___super:
3795 case tok::kw_decltype:
3796 case tok::identifier:
3797 ParseIdentifier: {
3798 // This identifier can only be a typedef name if we haven't already seen
3799 // a type-specifier. Without this check we misparse:
3800 // typedef int X; struct Y { short X; }; as 'short int'.
3801 if (DS.hasTypeSpecifier())
3802 goto DoneWithDeclSpec;
3803
3804 // If the token is an identifier named "__declspec" and Microsoft
3805 // extensions are not enabled, it is likely that there will be cascading
3806 // parse errors if this really is a __declspec attribute. Attempt to
3807 // recognize that scenario and recover gracefully.
3808 if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3809 Tok.getIdentifierInfo()->getName() == "__declspec") {
3810 Diag(Loc, diag::err_ms_attributes_not_enabled);
3811
3812 // The next token should be an open paren. If it is, eat the entire
3813 // attribute declaration and continue.
3814 if (NextToken().is(tok::l_paren)) {
3815 // Consume the __declspec identifier.
3816 ConsumeToken();
3817
3818 // Eat the parens and everything between them.
3819 BalancedDelimiterTracker T(*this, tok::l_paren);
3820 if (T.consumeOpen()) {
3821 assert(false && "Not a left paren?");
3822 return;
3823 }
3824 T.skipToEnd();
3825 continue;
3826 }
3827 }
3828
3829 // In C++, check to see if this is a scope specifier like foo::bar::, if
3830 // so handle it as such. This is important for ctor parsing.
3831 if (getLangOpts().CPlusPlus) {
3832 // C++20 [temp.spec] 13.9/6.
3833 // This disables the access checking rules for function template
3834 // explicit instantiation and explicit specialization:
3835 // - `return type`.
3836 SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3837
3838 const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
3839
3840 if (IsTemplateSpecOrInst)
3841 SAC.done();
3842
3843 if (Success) {
3844 if (IsTemplateSpecOrInst)
3845 SAC.redelay();
3846 DS.SetTypeSpecError();
3847 goto DoneWithDeclSpec;
3848 }
3849
3850 if (!Tok.is(tok::identifier))
3851 continue;
3852 }
3853
3854 // Check for need to substitute AltiVec keyword tokens.
3855 if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3856 break;
3857
3858 // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3859 // allow the use of a typedef name as a type specifier.
3860 if (DS.isTypeAltiVecVector())
3861 goto DoneWithDeclSpec;
3862
3863 if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3864 isObjCInstancetype()) {
3865 ParsedType TypeRep = Actions.ObjC().ActOnObjCInstanceType(Loc);
3866 assert(TypeRep);
3868 DiagID, TypeRep, Policy);
3869 if (isInvalid)
3870 break;
3871
3872 DS.SetRangeEnd(Loc);
3873 ConsumeToken();
3874 continue;
3875 }
3876
3877 // If we're in a context where the identifier could be a class name,
3878 // check whether this is a constructor declaration.
3879 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3880 Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3881 isConstructorDeclarator(/*Unqualified=*/true,
3882 /*DeductionGuide=*/false,
3883 DS.isFriendSpecified()))
3884 goto DoneWithDeclSpec;
3885
3886 ParsedType TypeRep = Actions.getTypeName(
3887 *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3888 false, false, nullptr, false, false,
3889 isClassTemplateDeductionContext(DSContext));
3890
3891 // If this is not a typedef name, don't parse it as part of the declspec,
3892 // it must be an implicit int or an error.
3893 if (!TypeRep) {
3894 if (TryAnnotateTypeConstraint())
3895 goto DoneWithDeclSpec;
3896 if (Tok.isNot(tok::identifier))
3897 continue;
3898 ParsedAttributes Attrs(AttrFactory);
3899 if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3900 if (!Attrs.empty()) {
3901 AttrsLastTime = true;
3902 attrs.takeAllAppendingFrom(Attrs);
3903 }
3904 continue;
3905 }
3906 goto DoneWithDeclSpec;
3907 }
3908
3909 // Likewise, if this is a context where the identifier could be a template
3910 // name, check whether this is a deduction guide declaration.
3911 CXXScopeSpec SS;
3912 if (getLangOpts().CPlusPlus17 &&
3913 (DSContext == DeclSpecContext::DSC_class ||
3914 DSContext == DeclSpecContext::DSC_top_level) &&
3915 Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3916 Tok.getLocation(), SS) &&
3917 isConstructorDeclarator(/*Unqualified*/ true,
3918 /*DeductionGuide*/ true))
3919 goto DoneWithDeclSpec;
3920
3922 DiagID, TypeRep, Policy);
3923 if (isInvalid)
3924 break;
3925
3926 DS.SetRangeEnd(Tok.getLocation());
3927 ConsumeToken(); // The identifier
3928
3929 // Objective-C supports type arguments and protocol references
3930 // following an Objective-C object or object pointer
3931 // type. Handle either one of them.
3932 if (Tok.is(tok::less) && getLangOpts().ObjC) {
3933 SourceLocation NewEndLoc;
3934 TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3935 Loc, TypeRep, /*consumeLastToken=*/true,
3936 NewEndLoc);
3937 if (NewTypeRep.isUsable()) {
3938 DS.UpdateTypeRep(NewTypeRep.get());
3939 DS.SetRangeEnd(NewEndLoc);
3940 }
3941 }
3942
3943 // Need to support trailing type qualifiers (e.g. "id<p> const").
3944 // If a type specifier follows, it will be diagnosed elsewhere.
3945 continue;
3946 }
3947
3948 // type-name or placeholder-specifier
3949 case tok::annot_template_id: {
3950 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3951
3952 if (TemplateId->hasInvalidName()) {
3953 DS.SetTypeSpecError();
3954 break;
3955 }
3956
3957 if (TemplateId->Kind == TNK_Concept_template) {
3958 // If we've already diagnosed that this type-constraint has invalid
3959 // arguments, drop it and just form 'auto' or 'decltype(auto)'.
3960 if (TemplateId->hasInvalidArgs())
3961 TemplateId = nullptr;
3962
3963 // Any of the following tokens are likely the start of the user
3964 // forgetting 'auto' or 'decltype(auto)', so diagnose.
3965 // Note: if updating this list, please make sure we update
3966 // isCXXDeclarationSpecifier's check for IsPlaceholderSpecifier to have
3967 // a matching list.
3968 if (NextToken().isOneOf(tok::identifier, tok::kw_const,
3969 tok::kw_volatile, tok::kw_restrict, tok::amp,
3970 tok::ampamp)) {
3971 Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3972 << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3973 // Attempt to continue as if 'auto' was placed here.
3974 isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3975 TemplateId, Policy);
3976 break;
3977 }
3978 if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3979 goto DoneWithDeclSpec;
3980
3981 if (TemplateId && !isInvalid && Actions.CheckTypeConstraint(TemplateId))
3982 TemplateId = nullptr;
3983
3984 ConsumeAnnotationToken();
3985 SourceLocation AutoLoc = Tok.getLocation();
3986 if (TryConsumeToken(tok::kw_decltype)) {
3987 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3988 if (Tracker.consumeOpen()) {
3989 // Something like `void foo(Iterator decltype i)`
3990 Diag(Tok, diag::err_expected) << tok::l_paren;
3991 } else {
3992 if (!TryConsumeToken(tok::kw_auto)) {
3993 // Something like `void foo(Iterator decltype(int) i)`
3994 Tracker.skipToEnd();
3995 Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3996 << FixItHint::CreateReplacement(SourceRange(AutoLoc,
3997 Tok.getLocation()),
3998 "auto");
3999 } else {
4000 Tracker.consumeClose();
4001 }
4002 }
4003 ConsumedEnd = Tok.getLocation();
4004 DS.setTypeArgumentRange(Tracker.getRange());
4005 // Even if something went wrong above, continue as if we've seen
4006 // `decltype(auto)`.
4007 isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
4008 DiagID, TemplateId, Policy);
4009 } else {
4010 isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
4011 TemplateId, Policy);
4012 }
4013 break;
4014 }
4015
4016 if (TemplateId->Kind != TNK_Type_template &&
4017 TemplateId->Kind != TNK_Undeclared_template) {
4018 // This template-id does not refer to a type name, so we're
4019 // done with the type-specifiers.
4020 goto DoneWithDeclSpec;
4021 }
4022
4023 // If we're in a context where the template-id could be a
4024 // constructor name or specialization, check whether this is a
4025 // constructor declaration.
4026 if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
4027 Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
4028 isConstructorDeclarator(/*Unqualified=*/true,
4029 /*DeductionGuide=*/false,
4030 DS.isFriendSpecified()))
4031 goto DoneWithDeclSpec;
4032
4033 // Turn the template-id annotation token into a type annotation
4034 // token, then try again to parse it as a type-specifier.
4035 CXXScopeSpec SS;
4036 AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
4037 continue;
4038 }
4039
4040 // Attributes support.
4041 case tok::kw___attribute:
4042 case tok::kw___declspec:
4043 ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), LateAttrs);
4044 continue;
4045
4046 // Microsoft single token adornments.
4047 case tok::kw___forceinline: {
4048 isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
4049 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
4050 SourceLocation AttrNameLoc = Tok.getLocation();
4051 DS.getAttributes().addNew(AttrName, AttrNameLoc, AttributeScopeInfo(),
4052 nullptr, 0, tok::kw___forceinline);
4053 break;
4054 }
4055
4056 case tok::kw___unaligned:
4057 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
4058 getLangOpts());
4059 break;
4060
4061 // __ptrauth qualifier.
4062 case tok::kw___ptrauth:
4063 ParsePtrauthQualifier(DS.getAttributes());
4064 continue;
4065
4066 case tok::kw___sptr:
4067 case tok::kw___uptr:
4068 case tok::kw___ptr64:
4069 case tok::kw___ptr32:
4070 case tok::kw___w64:
4071 case tok::kw___cdecl:
4072 case tok::kw___stdcall:
4073 case tok::kw___fastcall:
4074 case tok::kw___thiscall:
4075 case tok::kw___regcall:
4076 case tok::kw___vectorcall:
4077 ParseMicrosoftTypeAttributes(DS.getAttributes());
4078 continue;
4079
4080 case tok::kw___funcref:
4081 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
4082 continue;
4083
4084 // Borland single token adornments.
4085 case tok::kw___pascal:
4086 ParseBorlandTypeAttributes(DS.getAttributes());
4087 continue;
4088
4089 // OpenCL single token adornments.
4090 case tok::kw___kernel:
4091 ParseOpenCLKernelAttributes(DS.getAttributes());
4092 continue;
4093
4094 // CUDA/HIP single token adornments.
4095 case tok::kw___noinline__:
4096 ParseCUDAFunctionAttributes(DS.getAttributes());
4097 continue;
4098
4099 // Nullability type specifiers.
4100 case tok::kw__Nonnull:
4101 case tok::kw__Nullable:
4102 case tok::kw__Nullable_result:
4103 case tok::kw__Null_unspecified:
4104 ParseNullabilityTypeSpecifiers(DS.getAttributes());
4105 continue;
4106
4107 // Objective-C 'kindof' types.
4108 case tok::kw___kindof:
4109 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc,
4110 AttributeScopeInfo(), nullptr, 0,
4111 tok::kw___kindof);
4112 (void)ConsumeToken();
4113 continue;
4114
4115 // storage-class-specifier
4116 case tok::kw_typedef:
4118 PrevSpec, DiagID, Policy);
4119 isStorageClass = true;
4120 break;
4121 case tok::kw_extern:
4123 Diag(Tok, diag::ext_thread_before) << "extern";
4125 PrevSpec, DiagID, Policy);
4126 isStorageClass = true;
4127 break;
4128 case tok::kw___private_extern__:
4130 Loc, PrevSpec, DiagID, Policy);
4131 isStorageClass = true;
4132 break;
4133 case tok::kw_static:
4135 Diag(Tok, diag::ext_thread_before) << "static";
4137 PrevSpec, DiagID, Policy);
4138 isStorageClass = true;
4139 break;
4140 case tok::kw_auto:
4142 auto IsTypedefName = [&](const Token &T) {
4143 if (!T.is(tok::identifier))
4144 return false;
4145 IdentifierInfo *II = T.getIdentifierInfo();
4146 if (!II)
4147 return false;
4148 // Suppress diagnostics; the real parse will emit them later.
4149 LookupResult R(Actions, II, T.getLocation(),
4151 Actions.LookupName(R, getCurScope(),
4152 /*AllowBuiltinCreation=*/false);
4153 R.suppressDiagnostics();
4154 return R.isSingleResult() && isa<TypeDecl>(R.getFoundDecl());
4155 };
4156 auto MayBeTypeSpecifier = [&]() {
4157 // In pre-C23 C, auto can be used as a storage-class specifier.
4158 // C23 removes auto from the storage-class specifiers and repurposes
4159 // it for type inference (6.7.10).
4160 if (getLangOpts().C23 && DS.hasTypeSpecifier() &&
4162 return true;
4163
4164 unsigned I = 1;
4165 while (true) {
4166 const Token &T = GetLookAheadToken(I);
4167 if (isKnownToBeTypeSpecifier(T))
4168 return true;
4169
4170 // C23: a bare identifier that names a typedef is a type
4171 // specifier here, so `auto typedefName varName;` should be
4172 // parsed with `auto` as the storage-class specifier — not as
4173 // type inference. Without this check the parser would consume
4174 // `auto` as type-inference and then error on the missing
4175 // initializer for what it thinks is `typedefName`.
4176 if (getLangOpts().C23 && IsTypedefName(T))
4177 return true;
4178
4179 if (getLangOpts().C23 && isTypeSpecifierQualifier(T))
4180 ++I;
4181 else
4182 return false;
4183 }
4184 };
4185
4186 if (MayBeTypeSpecifier()) {
4188 PrevSpec, DiagID, Policy);
4189 if (!isInvalid && !getLangOpts().C23)
4190 Diag(Tok, diag::ext_auto_storage_class)
4192 } else
4193 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
4194 DiagID, Policy);
4195 } else
4197 PrevSpec, DiagID, Policy);
4198 isStorageClass = true;
4199 break;
4200 case tok::kw___auto_type:
4201 Diag(Tok, diag::ext_auto_type);
4203 DiagID, Policy);
4204 break;
4205 case tok::kw_register:
4207 PrevSpec, DiagID, Policy);
4208 isStorageClass = true;
4209 break;
4210 case tok::kw_mutable:
4212 PrevSpec, DiagID, Policy);
4213 isStorageClass = true;
4214 break;
4215 case tok::kw___thread:
4217 PrevSpec, DiagID);
4218 isStorageClass = true;
4219 break;
4220 case tok::kw_thread_local:
4221 if (getLangOpts().C23)
4222 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4223 // We map thread_local to _Thread_local in C23 mode so it retains the C
4224 // semantics rather than getting the C++ semantics.
4225 // FIXME: diagnostics will show _Thread_local when the user wrote
4226 // thread_local in source in C23 mode; we need some general way to
4227 // identify which way the user spelled the keyword in source.
4231 Loc, PrevSpec, DiagID);
4232 isStorageClass = true;
4233 break;
4234 case tok::kw__Thread_local:
4235 diagnoseUseOfC11Keyword(Tok);
4237 Loc, PrevSpec, DiagID);
4238 isStorageClass = true;
4239 break;
4240
4241 // function-specifier
4242 case tok::kw_inline:
4243 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
4244 break;
4245 case tok::kw_virtual:
4246 // C++ for OpenCL does not allow virtual function qualifier, to avoid
4247 // function pointers restricted in OpenCL v2.0 s6.9.a.
4248 if (getLangOpts().OpenCLCPlusPlus &&
4249 !getActions().getOpenCLOptions().isAvailableOption(
4250 "__cl_clang_function_pointers", getLangOpts())) {
4251 DiagID = diag::err_openclcxx_virtual_function;
4252 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4253 isInvalid = true;
4254 } else if (getLangOpts().HLSL) {
4255 DiagID = diag::err_hlsl_virtual_function;
4256 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4257 isInvalid = true;
4258 } else {
4259 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
4260 }
4261 break;
4262 case tok::kw_explicit: {
4263 SourceLocation ExplicitLoc = Loc;
4264 SourceLocation CloseParenLoc;
4265 ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
4266 ConsumedEnd = ExplicitLoc;
4267 ConsumeToken(); // kw_explicit
4268 if (Tok.is(tok::l_paren)) {
4269 if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
4270 DiagCompat(Tok.getLocation(), diag_compat::explicit_bool);
4271
4272 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
4273 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4274 Tracker.consumeOpen();
4275
4276 EnterExpressionEvaluationContext ConstantEvaluated(
4278
4280 ConsumedEnd = Tok.getLocation();
4281 if (ExplicitExpr.isUsable()) {
4282 CloseParenLoc = Tok.getLocation();
4283 Tracker.consumeClose();
4284 ExplicitSpec =
4285 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
4286 } else
4287 Tracker.skipToEnd();
4288 } else {
4289 Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
4290 }
4291 }
4292 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
4293 ExplicitSpec, CloseParenLoc);
4294 break;
4295 }
4296 case tok::kw__Noreturn:
4297 diagnoseUseOfC11Keyword(Tok);
4298 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
4299 break;
4300
4301 // friend
4302 case tok::kw_friend:
4303 if (DSContext == DeclSpecContext::DSC_class) {
4304 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
4305 Scope *CurS = getCurScope();
4306 if (!isInvalid && CurS)
4307 CurS->setFlags(CurS->getFlags() | Scope::FriendScope);
4308 } else {
4309 PrevSpec = ""; // not actually used by the diagnostic
4310 DiagID = diag::err_friend_invalid_in_context;
4311 isInvalid = true;
4312 }
4313 break;
4314
4315 // Modules
4316 case tok::kw___module_private__:
4317 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
4318 break;
4319
4320 // constexpr, consteval, constinit specifiers
4321 case tok::kw_constexpr:
4322 if (getLangOpts().C23)
4323 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4325 PrevSpec, DiagID);
4326 break;
4327 case tok::kw_consteval:
4329 PrevSpec, DiagID);
4330 break;
4331 case tok::kw_constinit:
4333 PrevSpec, DiagID);
4334 break;
4335
4336 // type-specifier
4337 case tok::kw_short:
4338 if (!getLangOpts().NativeInt16Type) {
4339 Diag(Tok, diag::err_unknown_typename) << Tok.getName();
4340 DS.SetTypeSpecError();
4341 DS.SetRangeEnd(Tok.getLocation());
4342 ConsumeToken();
4343 goto DoneWithDeclSpec;
4344 }
4346 DiagID, Policy);
4347 break;
4348 case tok::kw_long:
4351 DiagID, Policy);
4352 else
4354 PrevSpec, DiagID, Policy);
4355 break;
4356 case tok::kw___int64:
4358 PrevSpec, DiagID, Policy);
4359 break;
4360 case tok::kw_signed:
4361 isInvalid =
4362 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4363 break;
4364 case tok::kw_unsigned:
4366 DiagID);
4367 break;
4368 case tok::kw__Complex:
4369 if (!getLangOpts().C99)
4370 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4372 DiagID);
4373 break;
4374 case tok::kw__Imaginary:
4375 if (!getLangOpts().C99)
4376 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4378 DiagID);
4379 break;
4380 case tok::kw_void:
4381 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
4382 DiagID, Policy);
4383 break;
4384 case tok::kw_char:
4385 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
4386 DiagID, Policy);
4387 break;
4388 case tok::kw_int:
4389 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
4390 DiagID, Policy);
4391 break;
4392 case tok::kw__ExtInt:
4393 case tok::kw__BitInt: {
4394 DiagnoseBitIntUse(Tok);
4395 ExprResult ER = ParseExtIntegerArgument();
4396 if (ER.isInvalid())
4397 continue;
4398 isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
4399 ConsumedEnd = PrevTokLocation;
4400 break;
4401 }
4402 case tok::kw___int128:
4404 DiagID, Policy);
4405 break;
4406 case tok::kw_half:
4407 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
4408 DiagID, Policy);
4409 break;
4410 case tok::kw___bf16:
4412 DiagID, Policy);
4413 break;
4414 case tok::kw_float:
4415 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
4416 DiagID, Policy);
4417 break;
4418 case tok::kw_double:
4420 DiagID, Policy);
4421 break;
4422 case tok::kw__Float16:
4424 DiagID, Policy);
4425 break;
4426 case tok::kw__Accum:
4427 assert(getLangOpts().FixedPoint &&
4428 "This keyword is only used when fixed point types are enabled "
4429 "with `-ffixed-point`");
4430 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec, DiagID,
4431 Policy);
4432 break;
4433 case tok::kw__Fract:
4434 assert(getLangOpts().FixedPoint &&
4435 "This keyword is only used when fixed point types are enabled "
4436 "with `-ffixed-point`");
4437 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec, DiagID,
4438 Policy);
4439 break;
4440 case tok::kw__Sat:
4441 assert(getLangOpts().FixedPoint &&
4442 "This keyword is only used when fixed point types are enabled "
4443 "with `-ffixed-point`");
4444 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
4445 break;
4446 case tok::kw___float128:
4448 DiagID, Policy);
4449 break;
4450 case tok::kw___ibm128:
4452 DiagID, Policy);
4453 break;
4454 case tok::kw_wchar_t:
4455 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
4456 DiagID, Policy);
4457 break;
4458 case tok::kw_char8_t:
4459 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
4460 DiagID, Policy);
4461 break;
4462 case tok::kw_char16_t:
4464 DiagID, Policy);
4465 break;
4466 case tok::kw_char32_t:
4468 DiagID, Policy);
4469 break;
4470 case tok::kw_bool:
4471 if (getLangOpts().C23)
4472 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4473 [[fallthrough]];
4474 case tok::kw__Bool:
4475 if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
4476 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4477
4478 if (Tok.is(tok::kw_bool) &&
4481 PrevSpec = ""; // Not used by the diagnostic.
4482 DiagID = diag::err_bool_redeclaration;
4483 // For better error recovery.
4484 Tok.setKind(tok::identifier);
4485 isInvalid = true;
4486 } else {
4487 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
4488 DiagID, Policy);
4489 }
4490 break;
4491 case tok::kw__Decimal32:
4493 DiagID, Policy);
4494 break;
4495 case tok::kw__Decimal64:
4497 DiagID, Policy);
4498 break;
4499 case tok::kw__Decimal128:
4501 DiagID, Policy);
4502 break;
4503 case tok::kw___vector:
4504 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4505 break;
4506 case tok::kw___pixel:
4507 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4508 break;
4509 case tok::kw___bool:
4510 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4511 break;
4512 case tok::kw_pipe:
4513 if (!getLangOpts().OpenCL ||
4514 getLangOpts().getOpenCLCompatibleVersion() < 200) {
4515 // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4516 // should support the "pipe" word as identifier.
4517 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
4518 Tok.setKind(tok::identifier);
4519 goto DoneWithDeclSpec;
4520 } else if (!getLangOpts().OpenCLPipes) {
4521 DiagID = diag::err_opencl_unknown_type_specifier;
4522 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4523 isInvalid = true;
4524 } else
4525 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4526 break;
4527// We only need to enumerate each image type once.
4528#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4529#define IMAGE_WRITE_TYPE(Type, Id, Ext)
4530#define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4531 case tok::kw_##ImgType##_t: \
4532 if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4533 goto DoneWithDeclSpec; \
4534 break;
4535#include "clang/Basic/OpenCLImageTypes.def"
4536 case tok::kw___unknown_anytype:
4538 PrevSpec, DiagID, Policy);
4539 break;
4540
4541 // class-specifier:
4542 case tok::kw_class:
4543 case tok::kw_struct:
4544 case tok::kw___interface:
4545 case tok::kw_union: {
4546 tok::TokenKind Kind = Tok.getKind();
4547 ConsumeToken();
4548
4549 // These are attributes following class specifiers.
4550 // To produce better diagnostic, we parse them when
4551 // parsing class specifier.
4552 ParsedAttributes Attributes(AttrFactory);
4553 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4554 EnteringContext, DSContext, Attributes);
4555
4556 // If there are attributes following class specifier,
4557 // take them over and handle them here.
4558 if (!Attributes.empty()) {
4559 AttrsLastTime = true;
4560 attrs.takeAllAppendingFrom(Attributes);
4561 }
4562 continue;
4563 }
4564
4565 // enum-specifier:
4566 case tok::kw_enum:
4567 ConsumeToken();
4568 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4569 continue;
4570
4571 // cv-qualifier:
4572 case tok::kw_const:
4573 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4574 getLangOpts());
4575 break;
4576 case tok::kw_volatile:
4577 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4578 getLangOpts());
4579 break;
4580 case tok::kw_restrict:
4581 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4582 getLangOpts());
4583 break;
4584 case tok::kw___ob_wrap:
4585 if (!getLangOpts().OverflowBehaviorTypes) {
4586 Diag(Loc, diag::warn_overflow_behavior_keyword_disabled)
4587 << tok::getKeywordSpelling(Tok.getKind());
4588 break;
4589 }
4591 OverflowBehaviorType::OverflowBehaviorKind::Wrap, Loc, PrevSpec,
4592 DiagID);
4593 break;
4594 case tok::kw___ob_trap:
4595 if (!getLangOpts().OverflowBehaviorTypes) {
4596 Diag(Loc, diag::warn_overflow_behavior_keyword_disabled)
4597 << tok::getKeywordSpelling(Tok.getKind());
4598 break;
4599 }
4601 OverflowBehaviorType::OverflowBehaviorKind::Trap, Loc, PrevSpec,
4602 DiagID);
4603 break;
4604
4605 // C++ typename-specifier:
4606 case tok::kw_typename:
4608 DS.SetTypeSpecError();
4609 goto DoneWithDeclSpec;
4610 }
4611 if (!Tok.is(tok::kw_typename))
4612 continue;
4613 break;
4614
4615 // C23/GNU typeof support.
4616 case tok::kw_typeof:
4617 case tok::kw_typeof_unqual:
4618 ParseTypeofSpecifier(DS);
4619 continue;
4620
4621 case tok::annot_decltype:
4622 ParseDecltypeSpecifier(DS);
4623 continue;
4624
4625 case tok::annot_pack_indexing_type:
4626 ParsePackIndexingType(DS);
4627 continue;
4628
4629 case tok::annot_pragma_pack:
4630 HandlePragmaPack();
4631 continue;
4632
4633 case tok::annot_pragma_ms_pragma:
4634 HandlePragmaMSPragma();
4635 continue;
4636
4637 case tok::annot_pragma_ms_vtordisp:
4638 HandlePragmaMSVtorDisp();
4639 continue;
4640
4641 case tok::annot_pragma_ms_pointers_to_members:
4642 HandlePragmaMSPointersToMembers();
4643 continue;
4644
4645 case tok::annot_pragma_export:
4646 HandlePragmaExport();
4647 continue;
4648
4649#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
4650#include "clang/Basic/BuiltinTraits.inc"
4651 // HACK: libstdc++ already uses '__remove_cv' as an alias template so we
4652 // work around this by expecting all transform type traits to be suffixed
4653 // with '('. They're an identifier otherwise.
4654 if (!MaybeParseTypeTransformTypeSpecifier(DS))
4655 goto ParseIdentifier;
4656 continue;
4657
4658 case tok::kw__Atomic:
4659 // C11 6.7.2.4/4:
4660 // If the _Atomic keyword is immediately followed by a left parenthesis,
4661 // it is interpreted as a type specifier (with a type name), not as a
4662 // type qualifier.
4663 diagnoseUseOfC11Keyword(Tok);
4664 if (NextToken().is(tok::l_paren)) {
4665 ParseAtomicSpecifier(DS);
4666 continue;
4667 }
4668 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4669 getLangOpts());
4670 break;
4671
4672 // OpenCL address space qualifiers:
4673 case tok::kw___generic:
4674 // generic address space is introduced only in OpenCL v2.0
4675 // see OpenCL C Spec v2.0 s6.5.5
4676 // OpenCL v3.0 introduces __opencl_c_generic_address_space
4677 // feature macro to indicate if generic address space is supported
4678 if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4679 DiagID = diag::err_opencl_unknown_type_specifier;
4680 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4681 isInvalid = true;
4682 break;
4683 }
4684 [[fallthrough]];
4685 case tok::kw_private:
4686 // It's fine (but redundant) to check this for __generic on the
4687 // fallthrough path; we only form the __generic token in OpenCL mode.
4688 if (!getLangOpts().OpenCL)
4689 goto DoneWithDeclSpec;
4690 [[fallthrough]];
4691 case tok::kw___private:
4692 case tok::kw___global:
4693 case tok::kw___local:
4694 case tok::kw___constant:
4695 // OpenCL access qualifiers:
4696 case tok::kw___read_only:
4697 case tok::kw___write_only:
4698 case tok::kw___read_write:
4699 ParseOpenCLQualifiers(DS.getAttributes());
4700 break;
4701 case tok::kw_row_major:
4702 case tok::kw_column_major:
4703 case tok::kw_nointerpolation:
4704 case tok::kw_linear:
4705 case tok::kw_centroid:
4706 case tok::kw_noperspective:
4707 case tok::kw_sample:
4708 case tok::kw_center:
4709 case tok::kw_groupshared:
4710 case tok::kw_in:
4711 case tok::kw_inout:
4712 case tok::kw_out:
4713 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4714 ParseHLSLQualifiers(DS.getAttributes());
4715 continue;
4716
4717#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
4718 case tok::kw_##Name: \
4719 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##Name, Loc, PrevSpec, \
4720 DiagID, Policy); \
4721 break;
4722#include "clang/Basic/HLSLIntangibleTypes.def"
4723
4724#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
4725 case tok::kw_##Name: \
4726 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##Name, Loc, PrevSpec, \
4727 DiagID, Policy); \
4728 break;
4729#include "clang/Basic/HLSLPackedTypes.def"
4730
4731 case tok::less:
4732 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4733 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4734 // but we support it.
4735 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4736 goto DoneWithDeclSpec;
4737
4738 SourceLocation StartLoc = Tok.getLocation();
4739 SourceLocation EndLoc;
4740 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4741 if (Type.isUsable()) {
4742 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4743 PrevSpec, DiagID, Type.get(),
4744 Actions.getASTContext().getPrintingPolicy()))
4745 Diag(StartLoc, DiagID) << PrevSpec;
4746
4747 DS.SetRangeEnd(EndLoc);
4748 } else {
4749 DS.SetTypeSpecError();
4750 }
4751
4752 // Need to support trailing type qualifiers (e.g. "id<p> const").
4753 // If a type specifier follows, it will be diagnosed elsewhere.
4754 continue;
4755 }
4756
4757 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4758
4759 // If the specifier wasn't legal, issue a diagnostic.
4760 if (isInvalid) {
4761 assert(PrevSpec && "Method did not return previous specifier!");
4762 assert(DiagID);
4763
4764 if (DiagID == diag::ext_duplicate_declspec ||
4765 DiagID == diag::ext_warn_duplicate_declspec ||
4766 DiagID == diag::err_duplicate_declspec)
4767 Diag(Loc, DiagID) << PrevSpec
4769 SourceRange(Loc, DS.getEndLoc()));
4770 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4771 Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4772 << isStorageClass;
4773 } else
4774 Diag(Loc, DiagID) << PrevSpec;
4775 }
4776
4777 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4778 // After an error the next token can be an annotation token.
4780
4781 AttrsLastTime = false;
4782 }
4783}
4784
4786 Parser &P) {
4787
4789 return;
4790
4791 auto *RD = dyn_cast<RecordDecl>(DS.getRepAsDecl());
4792 // We're only interested in unnamed, non-anonymous struct
4793 if (!RD || !RD->getName().empty() || RD->isAnonymousStructOrUnion())
4794 return;
4795
4796 for (auto *I : RD->decls()) {
4797 auto *VD = dyn_cast<ValueDecl>(I);
4798 if (!VD)
4799 continue;
4800
4801 auto *CAT = VD->getType()->getAs<CountAttributedType>();
4802 if (!CAT)
4803 continue;
4804
4805 for (const auto &DD : CAT->dependent_decls()) {
4806 if (!RD->containsDecl(DD.getDecl())) {
4807 P.Diag(VD->getBeginLoc(), diag::err_count_attr_param_not_in_same_struct)
4808 << DD.getDecl() << CAT->getKind() << CAT->isArrayType();
4809 P.Diag(DD.getDecl()->getBeginLoc(),
4810 diag::note_flexible_array_counted_by_attr_field)
4811 << DD.getDecl();
4812 }
4813 }
4814 }
4815}
4816
4817void Parser::ParseStructDeclaration(
4818 ParsingDeclSpec &DS,
4819 llvm::function_ref<Decl *(ParsingFieldDeclarator &)> FieldsCallback,
4820 LateParsedAttrList *LateFieldAttrs) {
4821
4822 if (Tok.is(tok::kw___extension__)) {
4823 // __extension__ silences extension warnings in the subexpression.
4824 ExtensionRAIIObject O(Diags); // Use RAII to do this.
4825 ConsumeToken();
4826 return ParseStructDeclaration(DS, FieldsCallback, LateFieldAttrs);
4827 }
4828
4829 // Parse leading attributes.
4830 ParsedAttributes Attrs(AttrFactory);
4831 MaybeParseCXX11Attributes(Attrs);
4832
4833 // Parse the common specifier-qualifiers-list piece.
4834 ParseSpecifierQualifierList(DS);
4835
4836 // If there are no declarators, this is a free-standing declaration
4837 // specifier. Let the actions module cope with it.
4838 if (Tok.is(tok::semi)) {
4839 // C23 6.7.2.1p9 : "The optional attribute specifier sequence in a
4840 // member declaration appertains to each of the members declared by the
4841 // member declarator list; it shall not appear if the optional member
4842 // declarator list is omitted."
4843 ProhibitAttributes(Attrs);
4844 RecordDecl *AnonRecord = nullptr;
4845 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
4846 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
4847 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4848 DS.complete(TheDecl);
4849 return;
4850 }
4851
4852 // Read struct-declarators until we find the semicolon.
4853 bool FirstDeclarator = true;
4854 SourceLocation CommaLoc;
4855 while (true) {
4856 ParsingFieldDeclarator DeclaratorInfo(*this, DS, Attrs);
4857 DeclaratorInfo.D.setCommaLoc(CommaLoc);
4858
4859 // Attributes are only allowed here on successive declarators.
4860 if (!FirstDeclarator) {
4861 // However, this does not apply for [[]] attributes (which could show up
4862 // before or after the __attribute__ attributes).
4863 DiagnoseAndSkipCXX11Attributes();
4864 MaybeParseGNUAttributes(DeclaratorInfo.D);
4865 DiagnoseAndSkipCXX11Attributes();
4866 }
4867
4868 /// struct-declarator: declarator
4869 /// struct-declarator: declarator[opt] ':' constant-expression
4870 if (Tok.isNot(tok::colon)) {
4871 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4873 ParseDeclarator(DeclaratorInfo.D);
4874 } else
4875 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4876
4877 // Here, we now know that the unnamed struct is not an anonymous struct.
4878 // Report an error if a counted_by attribute refers to a field in a
4879 // different named struct.
4881
4882 if (TryConsumeToken(tok::colon)) {
4884 if (Res.isInvalid())
4885 SkipUntil(tok::semi, StopBeforeMatch);
4886 else
4887 DeclaratorInfo.BitfieldSize = Res.get();
4888 }
4889
4890 // If attributes exist after the declarator, parse them.
4891 MaybeParseGNUAttributes(DeclaratorInfo.D, LateFieldAttrs);
4892
4893 // We're done with this declarator; invoke the callback.
4894 Decl *Field = FieldsCallback(DeclaratorInfo);
4895 if (Field)
4896 DistributeCLateParsedAttrs(Field, LateFieldAttrs);
4897
4898 // If we don't have a comma, it is either the end of the list (a ';')
4899 // or an error, bail out.
4900 if (!TryConsumeToken(tok::comma, CommaLoc))
4901 return;
4902
4903 FirstDeclarator = false;
4904 }
4905}
4906
4907ParsedAttributes Parser::ParseLexedAttributeTokens(LateParsedAttribute &LPA) {
4908 // Create a fake EOF so that attribute parsing won't go off the end of the
4909 // attribute.
4910 Token AttrEnd = Token::createEof(Tok.getLocation(), LPA.Toks.data());
4911 LPA.Toks.push_back(AttrEnd);
4912
4913 // Append the current token at the end of the new token stream so that it
4914 // doesn't get lost.
4915 LPA.Toks.push_back(Tok);
4916 PP.EnterTokenStream(LPA.Toks, /*DisableMacroExpansion=*/true,
4917 /*IsReinject=*/true);
4918
4919 // Drop the current token and bring the first cached one. It's the same token
4920 // as when we entered this function.
4921 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
4922
4923 ParsedAttributes Attrs(AttrFactory);
4924
4925 ParseGNUAttributeArgs(&LPA.AttrName, LPA.AttrNameLoc, Attrs,
4926 /*EndLoc=*/nullptr, /*ScopeName=*/nullptr,
4927 SourceLocation(), ParsedAttr::Form::GNU(),
4928 /*D=*/nullptr);
4929
4930 // Due to a parsing error, we either went over the cached tokens or
4931 // there are still cached tokens left, so we skip the leftover tokens.
4932 while (Tok.isNot(tok::eof))
4934
4935 // Consume the fake EOF token if it's there
4936 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
4938
4939 return Attrs;
4940}
4941
4942void Parser::ParseLexedTypeAttribute(LateParsedTypeAttribute &LA,
4943 ParsedAttributes &OutAttrs) {
4944 assert(LA.Decls.size() <= 1 &&
4945 "late field attribute expects to have at most one declaration.");
4946
4947 ParsedAttributes Attrs = ParseLexedAttributeTokens(LA);
4948 OutAttrs.takeAllAppendingFrom(Attrs);
4949}
4950
4951void Parser::CompleteLateParsedTypeAttributes(
4953 for (LateParsedTypeAttribute *RawLTA : LateTypeAttrs) {
4954 std::unique_ptr<LateParsedTypeAttribute> LTA(RawLTA);
4955
4956 BoundsAttributedType *BATy = LTA->Info.TypeToComplete;
4957 if (!BATy || Actions.isLateParsedBoundsTypeRejected(BATy))
4958 continue;
4959
4960 ArrayRef<Decl *> Fields = LTA->Decls;
4961
4962 AttributeFactory AF;
4963 ParsedAttributes Attrs(AF);
4964 ParseLexedTypeAttribute(*LTA, Attrs);
4965
4966 // An unparseable argument leaves no attribute behind; already diagnosed.
4967 if (Attrs.empty())
4968 continue;
4969 assert(Attrs.size() == 1);
4970
4971 Expr *Arg = Attrs[0].getArgAsExpr(0);
4972 assert(Arg);
4973
4974 bool Valid = true;
4975 assert(!Fields.empty());
4976 for (Decl *FD : Fields)
4977 Valid &= Actions.ActOnLateParsedTypeAttrArgument(
4978 BATy, cast<FieldDecl>(FD), Arg);
4979
4980 if (Valid)
4981 Attrs[0].setUsedAsTypeAttr();
4982 else
4983 Attrs[0].setInvalid();
4984 }
4985 LateTypeAttrs.clear();
4986}
4987
4989 // Delegate to the Parser that created this attribute
4990 Self->ParseLexedTypeAttribute(*this, OutAttrs);
4991}
4992
4993void Parser::TakeTypeAttrsAppendingFrom(LateParsedAttrList &To,
4994 LateParsedAttrList &From) {
4995 LateParsedAttrList::iterator It =
4996 llvm::remove_if(From, [&](LateParsedAttribute *LA) {
4998 To.push_back(LA);
4999 return true;
5000 }
5001 return false;
5002 });
5003 From.erase(It, From.end());
5004}
5005
5006void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
5007 DeclSpec::TST TagType, RecordDecl *TagDecl) {
5008 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
5009 "parsing struct/union body");
5010 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
5011
5012 BalancedDelimiterTracker T(*this, tok::l_brace);
5013 if (T.consumeOpen())
5014 return;
5015
5017 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
5018
5019 // `LateAttrParseExperimentalExtOnly=true` requests that only attributes
5020 // marked with `LateAttrParseExperimentalExt` are late parsed.
5021 LateParsedAttrList LateFieldAttrs(/*PSoon=*/true,
5022 /*LateAttrParseExperimentalExtOnly=*/true);
5023
5024 // While we still have something to read, read the declarations in the struct.
5025 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
5026 Tok.isNot(tok::eof)) {
5027 // Each iteration of this loop reads one struct-declaration.
5028
5029 // Check for extraneous top-level semicolon.
5030 if (Tok.is(tok::semi)) {
5031 ConsumeExtraSemi(ExtraSemiKind::InsideStruct, TagType);
5032 continue;
5033 }
5034
5035 // Parse _Static_assert declaration.
5036 if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
5037 SourceLocation DeclEnd;
5038 ParseStaticAssertDeclaration(DeclEnd);
5039 continue;
5040 }
5041
5042 if (Tok.is(tok::annot_pragma_pack)) {
5043 HandlePragmaPack();
5044 continue;
5045 }
5046
5047 if (Tok.is(tok::annot_pragma_align)) {
5048 HandlePragmaAlign();
5049 continue;
5050 }
5051
5052 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
5053 // Result can be ignored, because it must be always empty.
5055 ParsedAttributes Attrs(AttrFactory);
5056 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
5057 continue;
5058 }
5059
5060 if (Tok.is(tok::annot_pragma_openacc)) {
5062 ParsedAttributes Attrs(AttrFactory);
5063 ParseOpenACCDirectiveDecl(AS, Attrs, TagType, TagDecl);
5064 continue;
5065 }
5066
5067 if (tok::isPragmaAnnotation(Tok.getKind())) {
5068 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
5070 TagType, Actions.getASTContext().getPrintingPolicy());
5071 ConsumeAnnotationToken();
5072 continue;
5073 }
5074
5075 if (!Tok.is(tok::at)) {
5076 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) -> Decl * {
5077 // Install the declarator into the current TagDecl.
5078 Decl *Field =
5079 Actions.ActOnField(getCurScope(), TagDecl,
5080 FD.D.getDeclSpec().getSourceRange().getBegin(),
5081 FD.D, FD.BitfieldSize);
5082 FD.complete(Field);
5083 return Field;
5084 };
5085
5086 // Parse all the comma separated declarators.
5087 ParsingDeclSpec DS(*this);
5088 ParseStructDeclaration(DS, CFieldCallback, &LateFieldAttrs);
5089 } else { // Handle @defs
5090 ConsumeToken();
5091 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
5092 Diag(Tok, diag::err_unexpected_at);
5093 SkipUntil(tok::semi);
5094 continue;
5095 }
5096 ConsumeToken();
5097 ExpectAndConsume(tok::l_paren);
5098 if (!Tok.is(tok::identifier)) {
5099 Diag(Tok, diag::err_expected) << tok::identifier;
5100 SkipUntil(tok::semi);
5101 continue;
5102 }
5103 SmallVector<Decl *, 16> Fields;
5104 Actions.ObjC().ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
5105 Tok.getIdentifierInfo(), Fields);
5106 ConsumeToken();
5107 ExpectAndConsume(tok::r_paren);
5108 }
5109
5110 if (TryConsumeToken(tok::semi))
5111 continue;
5112
5113 if (Tok.is(tok::r_brace)) {
5114 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
5115 break;
5116 }
5117
5118 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
5119 // Skip to end of block or statement to avoid ext-warning on extra ';'.
5120 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
5121 // If we stopped at a ';', eat it.
5122 TryConsumeToken(tok::semi);
5123 }
5124
5125 T.consumeClose();
5126
5127 ParsedAttributes attrs(AttrFactory);
5128 // If attributes exist after struct contents, parse them.
5129 MaybeParseGNUAttributes(attrs, &LateFieldAttrs);
5130
5131 SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
5132
5133 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
5134 T.getOpenLocation(), T.getCloseLocation(), attrs);
5135
5136 // Late parse field attributes if necessary.
5137 ParseLexedAttributeList(LateFieldAttrs, /*D=*/nullptr, /*EnterScope=*/false,
5138 /*OnDefinition=*/false);
5139 StructScope.Exit();
5140 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
5141}
5142
5143void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
5144 const ParsedTemplateInfo &TemplateInfo,
5145 AccessSpecifier AS, DeclSpecContext DSC) {
5146 // Parse the tag portion of this.
5147 if (Tok.is(tok::code_completion)) {
5148 // Code completion for an enum name.
5149 cutOffParsing();
5150 Actions.CodeCompletion().CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
5151 DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
5152 return;
5153 }
5154
5155 // If attributes exist after tag, parse them.
5156 ParsedAttributes attrs(AttrFactory);
5157 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
5158
5159 SourceLocation ScopedEnumKWLoc;
5160 bool IsScopedUsingClassTag = false;
5161
5162 // In C++11, recognize 'enum class' and 'enum struct'.
5163 if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
5164 DiagCompat(Tok, diag_compat::scoped_enum);
5165 IsScopedUsingClassTag = Tok.is(tok::kw_class);
5166 ScopedEnumKWLoc = ConsumeToken();
5167
5168 // Attributes are not allowed between these keywords. Diagnose,
5169 // but then just treat them like they appeared in the right place.
5170 ProhibitAttributes(attrs);
5171
5172 // They are allowed afterwards, though.
5173 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
5174 }
5175
5176 // C++11 [temp.explicit]p12:
5177 // The usual access controls do not apply to names used to specify
5178 // explicit instantiations.
5179 // We extend this to also cover explicit specializations. Note that
5180 // we don't suppress if this turns out to be an elaborated type
5181 // specifier.
5182 bool shouldDelayDiagsInTag =
5183 (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation ||
5184 TemplateInfo.Kind == ParsedTemplateKind::ExplicitSpecialization);
5185 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
5186
5187 // Determine whether this declaration is permitted to have an enum-base.
5188 AllowDefiningTypeSpec AllowEnumSpecifier =
5189 isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus);
5190 bool CanBeOpaqueEnumDeclaration =
5191 DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
5192 bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
5193 getLangOpts().MicrosoftExt) &&
5194 (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
5195 CanBeOpaqueEnumDeclaration);
5196
5197 // We use a temporary scope when parsing the name specifier for a
5198 // declaration with additional invalid type specifiers.
5199 CXXScopeSpec InvalidDeclScope;
5200 CXXScopeSpec &SS =
5201 DS.hasTypeSpecifier() ? InvalidDeclScope : DS.getTypeSpecScope();
5202 if (getLangOpts().CPlusPlus) {
5203 // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
5205
5206 CXXScopeSpec Spec;
5207 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
5208 /*ObjectHasErrors=*/false,
5209 /*EnteringContext=*/true))
5210 return;
5211
5212 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
5213 Diag(Tok, diag::err_expected) << tok::identifier;
5214 DS.SetTypeSpecError();
5215 if (Tok.isNot(tok::l_brace)) {
5216 // Has no name and is not a definition.
5217 // Skip the rest of this declarator, up until the comma or semicolon.
5218 SkipUntil(tok::comma, StopAtSemi);
5219 return;
5220 }
5221 }
5222
5223 SS = std::move(Spec);
5224 }
5225
5226 // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
5227 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
5228 Tok.isNot(tok::colon)) {
5229 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
5230
5231 DS.SetTypeSpecError();
5232 // Skip the rest of this declarator, up until the comma or semicolon.
5233 SkipUntil(tok::comma, StopAtSemi);
5234 return;
5235 }
5236
5237 // If an identifier is present, consume and remember it.
5238 IdentifierInfo *Name = nullptr;
5239 SourceLocation NameLoc;
5240 if (Tok.is(tok::identifier)) {
5241 Name = Tok.getIdentifierInfo();
5242 NameLoc = ConsumeToken();
5243 }
5244
5245 if (!Name && ScopedEnumKWLoc.isValid()) {
5246 // C++0x 7.2p2: The optional identifier shall not be omitted in the
5247 // declaration of a scoped enumeration.
5248 Diag(Tok, diag::err_scoped_enum_missing_identifier);
5249 ScopedEnumKWLoc = SourceLocation();
5250 IsScopedUsingClassTag = false;
5251 }
5252
5253 // Okay, end the suppression area. We'll decide whether to emit the
5254 // diagnostics in a second.
5255 if (shouldDelayDiagsInTag)
5256 diagsFromTag.done();
5257
5258 TypeResult BaseType;
5259 SourceRange BaseRange;
5260
5261 bool CanBeBitfield =
5262 getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
5263
5264 auto IsCXXTypeAhead = [this]() {
5265 RevertingTentativeParsingAction PA(*this);
5266 ConsumeToken();
5267 return Parser::isCXXTypeId(TentativeCXXTypeIdContext::Unambiguous);
5268 };
5269
5270 // Parse the fixed underlying type.
5271 if (Tok.is(tok::colon) &&
5272 (!ParsingGenericAssociationType || IsCXXTypeAhead())) {
5273 // This might be an enum-base or part of some unrelated enclosing context.
5274 //
5275 // 'enum E : base' is permitted in two circumstances:
5276 //
5277 // 1) As a defining-type-specifier, when followed by '{'.
5278 // 2) As the sole constituent of a complete declaration -- when DS is empty
5279 // and the next token is ';'.
5280 //
5281 // The restriction to defining-type-specifiers is important to allow parsing
5282 // a ? new enum E : int{}
5283 // _Generic(a, enum E : int{})
5284 // properly.
5285 //
5286 // One additional consideration applies:
5287 //
5288 // C++ [dcl.enum]p1:
5289 // A ':' following "enum nested-name-specifier[opt] identifier" within
5290 // the decl-specifier-seq of a member-declaration is parsed as part of
5291 // an enum-base.
5292 //
5293 // Other language modes supporting enumerations with fixed underlying types
5294 // do not have clear rules on this, so we disambiguate to determine whether
5295 // the tokens form a bit-field width or an enum-base.
5296
5297 if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
5298 // Outside C++11, do not interpret the tokens as an enum-base if they do
5299 // not make sense as one. In C++11, it's an error if this happens.
5301 Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
5302 } else if (CanHaveEnumBase || !ColonIsSacred) {
5303 SourceLocation ColonLoc = ConsumeToken();
5304
5305 // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
5306 // because under -fms-extensions,
5307 // enum E : int *p;
5308 // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
5309 DeclSpec DS(AttrFactory);
5310 // enum-base is not assumed to be a type and therefore requires the
5311 // typename keyword [p0634r3].
5312 ParseSpecifierQualifierList(DS, ImplicitTypenameContext::No, AS,
5313 DeclSpecContext::DSC_type_specifier);
5314 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
5316 BaseType = Actions.ActOnTypeName(DeclaratorInfo);
5317
5318 BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
5319
5320 if (!getLangOpts().ObjC) {
5321 if (getLangOpts().CPlusPlus)
5322 DiagCompat(ColonLoc, diag_compat::cxx_enum_fixed_underlying_type)
5323 << BaseRange;
5324 else if (getLangOpts().MicrosoftExt && !getLangOpts().C23)
5325 Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
5326 << BaseRange;
5327 else
5328 DiagCompat(ColonLoc, diag_compat::c_enum_fixed_underlying_type)
5329 << BaseRange;
5330 }
5331 }
5332 }
5333
5334 // There are four options here. If we have 'friend enum foo;' then this is a
5335 // friend declaration, and cannot have an accompanying definition. If we have
5336 // 'enum foo;', then this is a forward declaration. If we have
5337 // 'enum foo {...' then this is a definition. Otherwise we have something
5338 // like 'enum foo xyz', a reference.
5339 //
5340 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
5341 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
5342 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
5343 //
5344 TagUseKind TUK;
5345 if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
5347 else if (Tok.is(tok::l_brace)) {
5348 if (DS.isFriendSpecified()) {
5349 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
5350 << SourceRange(DS.getFriendSpecLoc());
5351 ConsumeBrace();
5352 SkipUntil(tok::r_brace, StopAtSemi);
5353 // Discard any other definition-only pieces.
5354 attrs.clear();
5355 ScopedEnumKWLoc = SourceLocation();
5356 IsScopedUsingClassTag = false;
5357 BaseType = TypeResult();
5358 TUK = TagUseKind::Friend;
5359 } else {
5361 }
5362 } else if (!isTypeSpecifier(DSC) &&
5363 (Tok.is(tok::semi) ||
5364 (Tok.isAtStartOfLine() &&
5365 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
5366 // An opaque-enum-declaration is required to be standalone (no preceding or
5367 // following tokens in the declaration). Sema enforces this separately by
5368 // diagnosing anything else in the DeclSpec.
5370 if (Tok.isNot(tok::semi)) {
5371 // A semicolon was missing after this declaration. Diagnose and recover.
5372 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5373 PP.EnterToken(Tok, /*IsReinject=*/true);
5374 Tok.setKind(tok::semi);
5375 }
5376 } else {
5378 }
5379
5380 bool IsElaboratedTypeSpecifier =
5382
5383 // If this is an elaborated type specifier nested in a larger declaration,
5384 // and we delayed diagnostics before, just merge them into the current pool.
5385 if (TUK == TagUseKind::Reference && shouldDelayDiagsInTag) {
5386 diagsFromTag.redelay();
5387 }
5388
5389 MultiTemplateParamsArg TParams;
5390 if (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate &&
5391 TUK != TagUseKind::Reference) {
5392 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
5393 // Skip the rest of this declarator, up until the comma or semicolon.
5394 Diag(Tok, diag::err_enum_template);
5395 SkipUntil(tok::comma, StopAtSemi);
5396 return;
5397 }
5398
5399 if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation) {
5400 // Enumerations can't be explicitly instantiated.
5401 DS.SetTypeSpecError();
5402 Diag(StartLoc, diag::err_explicit_instantiation_enum);
5403 return;
5404 }
5405
5406 assert(TemplateInfo.TemplateParams && "no template parameters");
5407 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
5408 TemplateInfo.TemplateParams->size());
5409 SS.setTemplateParamLists(TParams);
5410 }
5411
5412 if (!Name && TUK != TagUseKind::Definition) {
5413 Diag(Tok, diag::err_enumerator_unnamed_no_def);
5414
5415 DS.SetTypeSpecError();
5416 // Skip the rest of this declarator, up until the comma or semicolon.
5417 SkipUntil(tok::comma, StopAtSemi);
5418 return;
5419 }
5420
5421 // An elaborated-type-specifier has a much more constrained grammar:
5422 //
5423 // 'enum' nested-name-specifier[opt] identifier
5424 //
5425 // If we parsed any other bits, reject them now.
5426 //
5427 // MSVC and (for now at least) Objective-C permit a full enum-specifier
5428 // or opaque-enum-declaration anywhere.
5429 if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
5430 !getLangOpts().ObjC) {
5431 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
5432 diag::err_keyword_not_allowed,
5433 /*DiagnoseEmptyAttrs=*/true);
5434 if (BaseType.isUsable())
5435 Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
5436 << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
5437 else if (ScopedEnumKWLoc.isValid())
5438 Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
5439 << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
5440 }
5441
5442 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
5443
5444 SkipBodyInfo SkipBody;
5445 if (!Name && TUK == TagUseKind::Definition && Tok.is(tok::l_brace) &&
5446 NextToken().is(tok::identifier))
5447 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
5448 NextToken().getIdentifierInfo(),
5449 NextToken().getLocation());
5450
5451 bool Owned = false;
5452 bool IsDependent = false;
5453 const char *PrevSpec = nullptr;
5454 unsigned DiagID;
5455 Decl *TagDecl =
5456 Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS,
5457 Name, NameLoc, attrs, AS, DS.getModulePrivateSpecLoc(),
5458 TParams, Owned, IsDependent, ScopedEnumKWLoc,
5459 IsScopedUsingClassTag,
5460 BaseType, DSC == DeclSpecContext::DSC_type_specifier,
5461 DSC == DeclSpecContext::DSC_template_param ||
5462 DSC == DeclSpecContext::DSC_template_type_arg,
5463 OffsetOfState, &SkipBody).get();
5464
5465 if (SkipBody.ShouldSkip) {
5466 assert(TUK == TagUseKind::Definition && "can only skip a definition");
5467
5468 BalancedDelimiterTracker T(*this, tok::l_brace);
5469 T.consumeOpen();
5470 T.skipToEnd();
5471
5472 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5473 NameLoc.isValid() ? NameLoc : StartLoc,
5474 PrevSpec, DiagID, TagDecl, Owned,
5475 Actions.getASTContext().getPrintingPolicy()))
5476 Diag(StartLoc, DiagID) << PrevSpec;
5477 return;
5478 }
5479
5480 if (IsDependent) {
5481 // This enum has a dependent nested-name-specifier. Handle it as a
5482 // dependent tag.
5483 if (!Name) {
5484 DS.SetTypeSpecError();
5485 Diag(Tok, diag::err_expected_type_name_after_typename);
5486 return;
5487 }
5488
5489 TypeResult Type = Actions.ActOnDependentTag(
5490 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
5491 if (Type.isInvalid()) {
5492 DS.SetTypeSpecError();
5493 return;
5494 }
5495
5496 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
5497 NameLoc.isValid() ? NameLoc : StartLoc,
5498 PrevSpec, DiagID, Type.get(),
5499 Actions.getASTContext().getPrintingPolicy()))
5500 Diag(StartLoc, DiagID) << PrevSpec;
5501
5502 return;
5503 }
5504
5505 if (!TagDecl) {
5506 // The action failed to produce an enumeration tag. If this is a
5507 // definition, consume the entire definition.
5508 if (Tok.is(tok::l_brace) && TUK != TagUseKind::Reference) {
5509 ConsumeBrace();
5510 SkipUntil(tok::r_brace, StopAtSemi);
5511 }
5512
5513 DS.SetTypeSpecError();
5514 return;
5515 }
5516
5517 if (Tok.is(tok::l_brace) && TUK == TagUseKind::Definition) {
5518 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
5519 ParseEnumBody(StartLoc, D, &SkipBody);
5520 if (SkipBody.CheckSameAsPrevious &&
5521 !Actions.ActOnDuplicateDefinition(getCurScope(), TagDecl, SkipBody)) {
5522 DS.SetTypeSpecError();
5523 return;
5524 }
5525 }
5526
5527 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5528 NameLoc.isValid() ? NameLoc : StartLoc,
5529 PrevSpec, DiagID, TagDecl, Owned,
5530 Actions.getASTContext().getPrintingPolicy()))
5531 Diag(StartLoc, DiagID) << PrevSpec;
5532}
5533
5534void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl,
5535 SkipBodyInfo *SkipBody) {
5536 // Enter the scope of the enum body and start the definition.
5537 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
5538 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
5539
5540 BalancedDelimiterTracker T(*this, tok::l_brace);
5541 T.consumeOpen();
5542
5543 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
5544 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) {
5545 if (getLangOpts().MicrosoftExt)
5546 Diag(T.getOpenLocation(), diag::ext_ms_c_empty_enum_type)
5547 << SourceRange(T.getOpenLocation(), Tok.getLocation());
5548 else
5549 Diag(Tok, diag::err_empty_enum);
5550 }
5551
5552 SmallVector<Decl *, 32> EnumConstantDecls;
5553 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
5554
5555 Decl *LastEnumConstDecl = nullptr;
5556
5557 // Parse the enumerator-list.
5558 while (Tok.isNot(tok::r_brace)) {
5559 // Parse enumerator. If failed, try skipping till the start of the next
5560 // enumerator definition.
5561 if (Tok.isNot(tok::identifier)) {
5562 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
5563 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
5564 TryConsumeToken(tok::comma))
5565 continue;
5566 break;
5567 }
5568 IdentifierInfo *Ident = Tok.getIdentifierInfo();
5569 SourceLocation IdentLoc = ConsumeToken();
5570
5571 // If attributes exist after the enumerator, parse them.
5572 ParsedAttributes attrs(AttrFactory);
5573 MaybeParseGNUAttributes(attrs);
5574 if (isAllowedCXX11AttributeSpecifier()) {
5575 if (getLangOpts().CPlusPlus)
5576 DiagCompat(Tok.getLocation(), diag_compat::ns_enum_attribute)
5577 << 1 /*enumerator*/;
5578 ParseCXX11Attributes(attrs);
5579 }
5580
5581 SourceLocation EqualLoc;
5582 ExprResult AssignedVal;
5583 EnumAvailabilityDiags.emplace_back(*this);
5584
5585 EnterExpressionEvaluationContext ConstantEvaluated(
5587 if (TryConsumeToken(tok::equal, EqualLoc)) {
5589 if (AssignedVal.isInvalid())
5590 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
5591 }
5592
5593 // Install the enumerator constant into EnumDecl.
5594 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
5595 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
5596 EqualLoc, AssignedVal.get(), SkipBody);
5597 EnumAvailabilityDiags.back().done();
5598
5599 EnumConstantDecls.push_back(EnumConstDecl);
5600 LastEnumConstDecl = EnumConstDecl;
5601
5602 if (Tok.is(tok::identifier)) {
5603 // We're missing a comma between enumerators.
5604 SourceLocation Loc = getEndOfPreviousToken();
5605 Diag(Loc, diag::err_enumerator_list_missing_comma)
5606 << FixItHint::CreateInsertion(Loc, ", ");
5607 continue;
5608 }
5609
5610 // Emumerator definition must be finished, only comma or r_brace are
5611 // allowed here.
5612 SourceLocation CommaLoc;
5613 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
5614 if (EqualLoc.isValid())
5615 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
5616 << tok::comma;
5617 else
5618 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
5619 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
5620 if (TryConsumeToken(tok::comma, CommaLoc))
5621 continue;
5622 } else {
5623 break;
5624 }
5625 }
5626
5627 // If comma is followed by r_brace, emit appropriate warning.
5628 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
5629 if (getLangOpts().CPlusPlus)
5630 DiagCompat(CommaLoc, diag_compat::cxx_enumerator_list_comma)
5631 << FixItHint::CreateRemoval(CommaLoc);
5632 else if (!getLangOpts().C99)
5633 Diag(CommaLoc, diag::ext_enumerator_list_comma_c)
5634 << FixItHint::CreateRemoval(CommaLoc);
5635 break;
5636 }
5637 }
5638
5639 // Eat the }.
5640 T.consumeClose();
5641
5642 // If attributes exist after the identifier list, parse them.
5643 ParsedAttributes attrs(AttrFactory);
5644 MaybeParseGNUAttributes(attrs);
5645
5646 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
5647 getCurScope(), attrs);
5648
5649 // Now handle enum constant availability diagnostics.
5650 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
5651 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
5652 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
5653 EnumAvailabilityDiags[i].redelay();
5654 PD.complete(EnumConstantDecls[i]);
5655 }
5656
5657 EnumScope.Exit();
5658 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
5659
5660 // The next token must be valid after an enum definition. If not, a ';'
5661 // was probably forgotten.
5662 bool CanBeBitfield = getCurScope()->isClassScope();
5663 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
5664 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5665 // Push this token back into the preprocessor and change our current token
5666 // to ';' so that the rest of the code recovers as though there were an
5667 // ';' after the definition.
5668 PP.EnterToken(Tok, /*IsReinject=*/true);
5669 Tok.setKind(tok::semi);
5670 }
5671}
5672
5673bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
5674 switch (Tok.getKind()) {
5675 default: return false;
5676 // type-specifiers
5677 case tok::kw_short:
5678 case tok::kw_long:
5679 case tok::kw___int64:
5680 case tok::kw___int128:
5681 case tok::kw_signed:
5682 case tok::kw_unsigned:
5683 case tok::kw__Complex:
5684 case tok::kw__Imaginary:
5685 case tok::kw_void:
5686 case tok::kw_char:
5687 case tok::kw_wchar_t:
5688 case tok::kw_char8_t:
5689 case tok::kw_char16_t:
5690 case tok::kw_char32_t:
5691 case tok::kw_int:
5692 case tok::kw__ExtInt:
5693 case tok::kw__BitInt:
5694 case tok::kw___bf16:
5695 case tok::kw_half:
5696 case tok::kw_float:
5697 case tok::kw_double:
5698 case tok::kw__Accum:
5699 case tok::kw__Fract:
5700 case tok::kw__Float16:
5701 case tok::kw___float128:
5702 case tok::kw___ibm128:
5703 case tok::kw_bool:
5704 case tok::kw__Bool:
5705 case tok::kw__Decimal32:
5706 case tok::kw__Decimal64:
5707 case tok::kw__Decimal128:
5708 case tok::kw___vector:
5709#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5710#include "clang/Basic/OpenCLImageTypes.def"
5711#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
5712#include "clang/Basic/HLSLIntangibleTypes.def"
5713#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
5714#include "clang/Basic/HLSLPackedTypes.def"
5715
5716 // struct-or-union-specifier (C99) or class-specifier (C++)
5717 case tok::kw_class:
5718 case tok::kw_struct:
5719 case tok::kw___interface:
5720 case tok::kw_union:
5721 // enum-specifier
5722 case tok::kw_enum:
5723
5724 case tok::kw_typeof:
5725 case tok::kw_typeof_unqual:
5726
5727 // C11 _Atomic
5728 case tok::kw__Atomic:
5729
5730 // typedef-name
5731 case tok::annot_typename:
5732 return true;
5733 }
5734}
5735
5736bool Parser::isTypeSpecifierQualifier(const Token &Tok) {
5737 switch (Tok.getKind()) {
5738 default: return false;
5739
5740 case tok::identifier: // foo::bar
5741 if (TryAltiVecVectorToken())
5742 return true;
5743 [[fallthrough]];
5744 case tok::kw_typename: // typename T::type
5745 // Annotate typenames and C++ scope specifiers. If we get one, just
5746 // recurse to handle whatever we get.
5748 return true;
5749 if (getCurToken().is(tok::identifier))
5750 return false;
5751 return isTypeSpecifierQualifier(getCurToken());
5752
5753 case tok::coloncolon: // ::foo::bar
5754 if (NextToken().is(tok::kw_new) || // ::new
5755 NextToken().is(tok::kw_delete)) // ::delete
5756 return false;
5757
5759 return true;
5760 return isTypeSpecifierQualifier(getCurToken());
5761
5762 // GNU attributes support.
5763 case tok::kw___attribute:
5764 // C23/GNU typeof support.
5765 case tok::kw_typeof:
5766 case tok::kw_typeof_unqual:
5767
5768 // type-specifiers
5769 case tok::kw_short:
5770 case tok::kw_long:
5771 case tok::kw___int64:
5772 case tok::kw___int128:
5773 case tok::kw_signed:
5774 case tok::kw_unsigned:
5775 case tok::kw__Complex:
5776 case tok::kw__Imaginary:
5777 case tok::kw_void:
5778 case tok::kw_char:
5779 case tok::kw_wchar_t:
5780 case tok::kw_char8_t:
5781 case tok::kw_char16_t:
5782 case tok::kw_char32_t:
5783 case tok::kw_int:
5784 case tok::kw__ExtInt:
5785 case tok::kw__BitInt:
5786 case tok::kw_half:
5787 case tok::kw___bf16:
5788 case tok::kw_float:
5789 case tok::kw_double:
5790 case tok::kw__Accum:
5791 case tok::kw__Fract:
5792 case tok::kw__Float16:
5793 case tok::kw___float128:
5794 case tok::kw___ibm128:
5795 case tok::kw_bool:
5796 case tok::kw__Bool:
5797 case tok::kw__Decimal32:
5798 case tok::kw__Decimal64:
5799 case tok::kw__Decimal128:
5800 case tok::kw___vector:
5801#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5802#include "clang/Basic/OpenCLImageTypes.def"
5803#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
5804#include "clang/Basic/HLSLIntangibleTypes.def"
5805#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
5806#include "clang/Basic/HLSLPackedTypes.def"
5807
5808 // struct-or-union-specifier (C99) or class-specifier (C++)
5809 case tok::kw_class:
5810 case tok::kw_struct:
5811 case tok::kw___interface:
5812 case tok::kw_union:
5813 // enum-specifier
5814 case tok::kw_enum:
5815
5816 // type-qualifier
5817 case tok::kw_const:
5818 case tok::kw_volatile:
5819 case tok::kw_restrict:
5820 case tok::kw___ob_wrap:
5821 case tok::kw___ob_trap:
5822 case tok::kw__Sat:
5823
5824 // Debugger support.
5825 case tok::kw___unknown_anytype:
5826
5827 // typedef-name
5828 case tok::annot_typename:
5829 return true;
5830
5831 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5832 case tok::less:
5833 return getLangOpts().ObjC;
5834
5835 case tok::kw___cdecl:
5836 case tok::kw___stdcall:
5837 case tok::kw___fastcall:
5838 case tok::kw___thiscall:
5839 case tok::kw___regcall:
5840 case tok::kw___vectorcall:
5841 case tok::kw___w64:
5842 case tok::kw___ptr64:
5843 case tok::kw___ptr32:
5844 case tok::kw___pascal:
5845 case tok::kw___unaligned:
5846 case tok::kw___ptrauth:
5847
5848 case tok::kw__Nonnull:
5849 case tok::kw__Nullable:
5850 case tok::kw__Nullable_result:
5851 case tok::kw__Null_unspecified:
5852
5853 case tok::kw___kindof:
5854
5855 case tok::kw___private:
5856 case tok::kw___local:
5857 case tok::kw___global:
5858 case tok::kw___constant:
5859 case tok::kw___generic:
5860 case tok::kw___read_only:
5861 case tok::kw___read_write:
5862 case tok::kw___write_only:
5863 case tok::kw___funcref:
5864 return true;
5865
5866 case tok::kw_private:
5867 return getLangOpts().OpenCL;
5868
5869 // C11 _Atomic
5870 case tok::kw__Atomic:
5871 return true;
5872
5873 // HLSL type qualifiers
5874 case tok::kw_nointerpolation:
5875 case tok::kw_linear:
5876 case tok::kw_centroid:
5877 case tok::kw_noperspective:
5878 case tok::kw_sample:
5879 case tok::kw_center:
5880 case tok::kw_groupshared:
5881 case tok::kw_in:
5882 case tok::kw_inout:
5883 case tok::kw_out:
5884 case tok::kw_row_major:
5885 case tok::kw_column_major:
5886 return getLangOpts().HLSL;
5887 }
5888}
5889
5890Parser::DeclGroupPtrTy Parser::ParseTopLevelStmtDecl() {
5891 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode");
5892
5893 // Parse a top-level-stmt.
5894 Parser::StmtVector Stmts;
5895 ParsedStmtContext SubStmtCtx = ParsedStmtContext();
5898 TopLevelStmtDecl *TLSD = Actions.ActOnStartTopLevelStmtDecl(getCurScope());
5899 StmtResult R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
5900 Actions.ActOnFinishTopLevelStmtDecl(TLSD, R.get());
5901 if (!R.isUsable()) {
5902 R = Actions.ActOnNullStmt(Tok.getLocation());
5903 TLSD->setStmt(R.get());
5904 }
5905
5906 if (Tok.is(tok::eof) && Tok.getEofData()) {
5907 ConsumeToken();
5908 TLSD->setSemiMissing();
5909 }
5910
5911 SmallVector<Decl *, 2> DeclsInGroup;
5912 DeclsInGroup.push_back(TLSD);
5913
5914 // Currently happens for things like -fms-extensions and use `__if_exists`.
5915 for (Stmt *S : Stmts) {
5916 // Here we should be safe as `__if_exists` and friends are not introducing
5917 // new variables which need to live outside file scope.
5918 TopLevelStmtDecl *D = Actions.ActOnStartTopLevelStmtDecl(getCurScope());
5919 Actions.ActOnFinishTopLevelStmtDecl(D, S);
5920 DeclsInGroup.push_back(D);
5921 }
5922
5923 return Actions.BuildDeclaratorGroup(DeclsInGroup);
5924}
5925
5926bool Parser::isDeclarationSpecifier(
5927 ImplicitTypenameContext AllowImplicitTypename,
5928 bool DisambiguatingWithExpression) {
5929 switch (Tok.getKind()) {
5930 default: return false;
5931
5932 // OpenCL 2.0 and later define this keyword.
5933 case tok::kw_pipe:
5934 return getLangOpts().OpenCL &&
5936
5937 case tok::identifier: // foo::bar
5938 // Unfortunate hack to support "Class.factoryMethod" notation.
5939 if (getLangOpts().ObjC && NextToken().is(tok::period))
5940 return false;
5941 if (TryAltiVecVectorToken())
5942 return true;
5943 [[fallthrough]];
5944 case tok::kw_decltype: // decltype(T())::type
5945 case tok::kw_typename: // typename T::type
5946 // Annotate typenames and C++ scope specifiers. If we get one, just
5947 // recurse to handle whatever we get.
5948 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
5949 return true;
5950 if (TryAnnotateTypeConstraint())
5951 return true;
5952 if (Tok.is(tok::identifier))
5953 return false;
5954
5955 // If we're in Objective-C and we have an Objective-C class type followed
5956 // by an identifier and then either ':' or ']', in a place where an
5957 // expression is permitted, then this is probably a class message send
5958 // missing the initial '['. In this case, we won't consider this to be
5959 // the start of a declaration.
5960 if (DisambiguatingWithExpression &&
5961 isStartOfObjCClassMessageMissingOpenBracket())
5962 return false;
5963
5964 return isDeclarationSpecifier(AllowImplicitTypename);
5965
5966 case tok::coloncolon: // ::foo::bar
5967 if (!getLangOpts().CPlusPlus)
5968 return false;
5969 if (NextToken().is(tok::kw_new) || // ::new
5970 NextToken().is(tok::kw_delete)) // ::delete
5971 return false;
5972
5973 // Annotate typenames and C++ scope specifiers. If we get one, just
5974 // recurse to handle whatever we get.
5976 return true;
5977 return isDeclarationSpecifier(ImplicitTypenameContext::No);
5978
5979 // storage-class-specifier
5980 case tok::kw_typedef:
5981 case tok::kw_extern:
5982 case tok::kw___private_extern__:
5983 case tok::kw_static:
5984 case tok::kw_auto:
5985 case tok::kw___auto_type:
5986 case tok::kw_register:
5987 case tok::kw___thread:
5988 case tok::kw_thread_local:
5989 case tok::kw__Thread_local:
5990
5991 // Modules
5992 case tok::kw___module_private__:
5993
5994 // Debugger support
5995 case tok::kw___unknown_anytype:
5996
5997 // type-specifiers
5998 case tok::kw_short:
5999 case tok::kw_long:
6000 case tok::kw___int64:
6001 case tok::kw___int128:
6002 case tok::kw_signed:
6003 case tok::kw_unsigned:
6004 case tok::kw__Complex:
6005 case tok::kw__Imaginary:
6006 case tok::kw_void:
6007 case tok::kw_char:
6008 case tok::kw_wchar_t:
6009 case tok::kw_char8_t:
6010 case tok::kw_char16_t:
6011 case tok::kw_char32_t:
6012
6013 case tok::kw_int:
6014 case tok::kw__ExtInt:
6015 case tok::kw__BitInt:
6016 case tok::kw_half:
6017 case tok::kw___bf16:
6018 case tok::kw_float:
6019 case tok::kw_double:
6020 case tok::kw__Accum:
6021 case tok::kw__Fract:
6022 case tok::kw__Float16:
6023 case tok::kw___float128:
6024 case tok::kw___ibm128:
6025 case tok::kw_bool:
6026 case tok::kw__Bool:
6027 case tok::kw__Decimal32:
6028 case tok::kw__Decimal64:
6029 case tok::kw__Decimal128:
6030 case tok::kw___vector:
6031
6032 // struct-or-union-specifier (C99) or class-specifier (C++)
6033 case tok::kw_class:
6034 case tok::kw_struct:
6035 case tok::kw_union:
6036 case tok::kw___interface:
6037 // enum-specifier
6038 case tok::kw_enum:
6039
6040 // type-qualifier
6041 case tok::kw_const:
6042 case tok::kw_volatile:
6043 case tok::kw_restrict:
6044 case tok::kw___ob_wrap:
6045 case tok::kw___ob_trap:
6046 case tok::kw__Sat:
6047
6048 // function-specifier
6049 case tok::kw_inline:
6050 case tok::kw_virtual:
6051 case tok::kw_explicit:
6052 case tok::kw__Noreturn:
6053
6054 // alignment-specifier
6055 case tok::kw__Alignas:
6056
6057 // friend keyword.
6058 case tok::kw_friend:
6059
6060 // static_assert-declaration
6061 case tok::kw_static_assert:
6062 case tok::kw__Static_assert:
6063
6064 // C23/GNU typeof support.
6065 case tok::kw_typeof:
6066 case tok::kw_typeof_unqual:
6067
6068 // GNU attributes.
6069 case tok::kw___attribute:
6070
6071 // C++11 decltype and constexpr.
6072 case tok::annot_decltype:
6073 case tok::annot_pack_indexing_type:
6074 case tok::kw_constexpr:
6075
6076 // C++20 consteval and constinit.
6077 case tok::kw_consteval:
6078 case tok::kw_constinit:
6079
6080 // C11 _Atomic
6081 case tok::kw__Atomic:
6082 return true;
6083
6084 case tok::kw_alignas:
6085 // alignas is a type-specifier-qualifier in C23, which is a kind of
6086 // declaration-specifier. Outside of C23 mode (including in C++), it is not.
6087 return getLangOpts().C23;
6088
6089 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
6090 case tok::less:
6091 return getLangOpts().ObjC;
6092
6093 // typedef-name
6094 case tok::annot_typename:
6095 return !DisambiguatingWithExpression ||
6096 !isStartOfObjCClassMessageMissingOpenBracket();
6097
6098 // placeholder-type-specifier
6099 case tok::annot_template_id: {
6100 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
6101 if (TemplateId->hasInvalidName())
6102 return true;
6103 // FIXME: What about type templates that have only been annotated as
6104 // annot_template_id, not as annot_typename?
6105 return isTypeConstraintAnnotation() &&
6106 (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
6107 }
6108
6109 case tok::annot_cxxscope: {
6110 TemplateIdAnnotation *TemplateId =
6111 NextToken().is(tok::annot_template_id)
6112 ? takeTemplateIdAnnotation(NextToken())
6113 : nullptr;
6114 if (TemplateId && TemplateId->hasInvalidName())
6115 return true;
6116 // FIXME: What about type templates that have only been annotated as
6117 // annot_template_id, not as annot_typename?
6118 if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
6119 return true;
6120 return isTypeConstraintAnnotation() &&
6121 GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
6122 }
6123
6124 case tok::kw___declspec:
6125 case tok::kw___cdecl:
6126 case tok::kw___stdcall:
6127 case tok::kw___fastcall:
6128 case tok::kw___thiscall:
6129 case tok::kw___regcall:
6130 case tok::kw___vectorcall:
6131 case tok::kw___w64:
6132 case tok::kw___sptr:
6133 case tok::kw___uptr:
6134 case tok::kw___ptr64:
6135 case tok::kw___ptr32:
6136 case tok::kw___forceinline:
6137 case tok::kw___pascal:
6138 case tok::kw___unaligned:
6139 case tok::kw___ptrauth:
6140
6141 case tok::kw__Nonnull:
6142 case tok::kw__Nullable:
6143 case tok::kw__Nullable_result:
6144 case tok::kw__Null_unspecified:
6145
6146 case tok::kw___kindof:
6147
6148 case tok::kw___private:
6149 case tok::kw___local:
6150 case tok::kw___global:
6151 case tok::kw___constant:
6152 case tok::kw___generic:
6153 case tok::kw___read_only:
6154 case tok::kw___read_write:
6155 case tok::kw___write_only:
6156#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
6157#include "clang/Basic/OpenCLImageTypes.def"
6158#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
6159#include "clang/Basic/HLSLIntangibleTypes.def"
6160#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
6161#include "clang/Basic/HLSLPackedTypes.def"
6162
6163 case tok::kw___funcref:
6164 case tok::kw_groupshared:
6165 return true;
6166
6167 case tok::kw_nointerpolation:
6168 case tok::kw_linear:
6169 case tok::kw_centroid:
6170 case tok::kw_noperspective:
6171 case tok::kw_sample:
6172 case tok::kw_center:
6173 case tok::kw_row_major:
6174 case tok::kw_column_major:
6175 return getLangOpts().HLSL;
6176
6177 case tok::kw_private:
6178 return getLangOpts().OpenCL;
6179 }
6180}
6181
6182bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide,
6184 const ParsedTemplateInfo *TemplateInfo) {
6185 RevertingTentativeParsingAction TPA(*this);
6186 // Parse the C++ scope specifier.
6187 CXXScopeSpec SS;
6188 if (TemplateInfo && TemplateInfo->TemplateParams)
6189 SS.setTemplateParamLists(*TemplateInfo->TemplateParams);
6190
6191 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6192 /*ObjectHasErrors=*/false,
6193 /*EnteringContext=*/true)) {
6194 return false;
6195 }
6196
6197 // Parse the constructor name.
6198 if (Tok.is(tok::identifier)) {
6199 // We already know that we have a constructor name; just consume
6200 // the token.
6201 ConsumeToken();
6202 } else if (Tok.is(tok::annot_template_id)) {
6203 ConsumeAnnotationToken();
6204 } else {
6205 return false;
6206 }
6207
6208 // There may be attributes here, appertaining to the constructor name or type
6209 // we just stepped past.
6210 SkipCXX11Attributes();
6211
6212 // Current class name must be followed by a left parenthesis.
6213 if (Tok.isNot(tok::l_paren)) {
6214 return false;
6215 }
6216 ConsumeParen();
6217
6218 // A right parenthesis, or ellipsis followed by a right parenthesis signals
6219 // that we have a constructor.
6220 if (Tok.is(tok::r_paren) ||
6221 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
6222 return true;
6223 }
6224
6225 // A C++11 attribute here signals that we have a constructor, and is an
6226 // attribute on the first constructor parameter.
6227 if (isCXX11AttributeSpecifier(/*Disambiguate=*/false,
6228 /*OuterMightBeMessageSend=*/true) !=
6230 return true;
6231 }
6232
6233 // If we need to, enter the specified scope.
6234 DeclaratorScopeObj DeclScopeObj(*this, SS);
6235 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
6236 DeclScopeObj.EnterDeclaratorScope();
6237
6238 // Optionally skip Microsoft attributes.
6239 ParsedAttributes Attrs(AttrFactory);
6240 MaybeParseMicrosoftAttributes(Attrs);
6241
6242 // Check whether the next token(s) are part of a declaration
6243 // specifier, in which case we have the start of a parameter and,
6244 // therefore, we know that this is a constructor.
6245 // Due to an ambiguity with implicit typename, the above is not enough.
6246 // Additionally, check to see if we are a friend.
6247 // If we parsed a scope specifier as well as friend,
6248 // we might be parsing a friend constructor.
6249 bool IsConstructor = false;
6250 ImplicitTypenameContext ITC = IsFriend && !SS.isSet()
6253 // Constructors cannot have this parameters, but we support that scenario here
6254 // to improve diagnostic.
6255 if (Tok.is(tok::kw_this)) {
6256 ConsumeToken();
6257 return isDeclarationSpecifier(ITC);
6258 }
6259
6260 if (isDeclarationSpecifier(ITC))
6261 IsConstructor = true;
6262 else if (Tok.is(tok::identifier) ||
6263 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
6264 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
6265 // This might be a parenthesized member name, but is more likely to
6266 // be a constructor declaration with an invalid argument type. Keep
6267 // looking.
6268 if (Tok.is(tok::annot_cxxscope))
6269 ConsumeAnnotationToken();
6270 ConsumeToken();
6271
6272 // If this is not a constructor, we must be parsing a declarator,
6273 // which must have one of the following syntactic forms (see the
6274 // grammar extract at the start of ParseDirectDeclarator):
6275 switch (Tok.getKind()) {
6276 case tok::l_paren:
6277 // C(X ( int));
6278 case tok::l_square:
6279 // C(X [ 5]);
6280 // C(X [ [attribute]]);
6281 case tok::coloncolon:
6282 // C(X :: Y);
6283 // C(X :: *p);
6284 // Assume this isn't a constructor, rather than assuming it's a
6285 // constructor with an unnamed parameter of an ill-formed type.
6286 break;
6287
6288 case tok::r_paren:
6289 // C(X )
6290
6291 // Skip past the right-paren and any following attributes to get to
6292 // the function body or trailing-return-type.
6293 ConsumeParen();
6294 SkipCXX11Attributes();
6295
6296 if (DeductionGuide) {
6297 // C(X) -> ... is a deduction guide.
6298 IsConstructor = Tok.is(tok::arrow);
6299 break;
6300 }
6301 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
6302 // Assume these were meant to be constructors:
6303 // C(X) : (the name of a bit-field cannot be parenthesized).
6304 // C(X) try (this is otherwise ill-formed).
6305 IsConstructor = true;
6306 }
6307 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
6308 // If we have a constructor name within the class definition,
6309 // assume these were meant to be constructors:
6310 // C(X) {
6311 // C(X) ;
6312 // ... because otherwise we would be declaring a non-static data
6313 // member that is ill-formed because it's of the same type as its
6314 // surrounding class.
6315 //
6316 // FIXME: We can actually do this whether or not the name is qualified,
6317 // because if it is qualified in this context it must be being used as
6318 // a constructor name.
6319 // currently, so we're somewhat conservative here.
6320 IsConstructor = IsUnqualified;
6321 }
6322 break;
6323
6324 default:
6325 IsConstructor = true;
6326 break;
6327 }
6328 }
6329 return IsConstructor;
6330}
6331
6332void Parser::ParseTypeQualifierListOpt(
6333 DeclSpec &DS, unsigned AttrReqs, bool AtomicOrPtrauthAllowed,
6334 bool IdentifierRequired, llvm::function_ref<void()> CodeCompletionHandler,
6335 LateParsedAttrList *LateAttrs) {
6336 if ((AttrReqs & AR_CXX11AttributesParsed) &&
6337 isAllowedCXX11AttributeSpecifier()) {
6338 ParsedAttributes Attrs(AttrFactory);
6339 ParseCXX11Attributes(Attrs);
6341 }
6342
6343 SourceLocation EndLoc;
6344
6345 while (true) {
6346 bool isInvalid = false;
6347 const char *PrevSpec = nullptr;
6348 unsigned DiagID = 0;
6349 SourceLocation Loc = Tok.getLocation();
6350
6351 switch (Tok.getKind()) {
6352 case tok::code_completion:
6353 cutOffParsing();
6354 if (CodeCompletionHandler)
6355 CodeCompletionHandler();
6356 else
6357 Actions.CodeCompletion().CodeCompleteTypeQualifiers(DS);
6358 return;
6359
6360 case tok::kw_const:
6361 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
6362 getLangOpts());
6363 break;
6364 case tok::kw_volatile:
6365 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
6366 getLangOpts());
6367 break;
6368 case tok::kw_restrict:
6369 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
6370 getLangOpts());
6371 break;
6372 case tok::kw___ob_wrap:
6373 if (!getLangOpts().OverflowBehaviorTypes) {
6374 Diag(Loc, diag::warn_overflow_behavior_keyword_disabled)
6375 << tok::getKeywordSpelling(Tok.getKind());
6376 break;
6377 }
6379 OverflowBehaviorType::OverflowBehaviorKind::Wrap, Loc, PrevSpec,
6380 DiagID);
6381 break;
6382 case tok::kw___ob_trap:
6383 if (!getLangOpts().OverflowBehaviorTypes) {
6384 Diag(Loc, diag::warn_overflow_behavior_keyword_disabled)
6385 << tok::getKeywordSpelling(Tok.getKind());
6386 break;
6387 }
6389 OverflowBehaviorType::OverflowBehaviorKind::Trap, Loc, PrevSpec,
6390 DiagID);
6391 break;
6392 case tok::kw__Atomic:
6393 if (!AtomicOrPtrauthAllowed)
6394 goto DoneWithTypeQuals;
6395 diagnoseUseOfC11Keyword(Tok);
6396 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
6397 getLangOpts());
6398 break;
6399
6400 // OpenCL qualifiers:
6401 case tok::kw_private:
6402 if (!getLangOpts().OpenCL)
6403 goto DoneWithTypeQuals;
6404 [[fallthrough]];
6405 case tok::kw___private:
6406 case tok::kw___global:
6407 case tok::kw___local:
6408 case tok::kw___constant:
6409 case tok::kw___generic:
6410 case tok::kw___read_only:
6411 case tok::kw___write_only:
6412 case tok::kw___read_write:
6413 ParseOpenCLQualifiers(DS.getAttributes());
6414 break;
6415
6416 case tok::kw_groupshared:
6417 case tok::kw_in:
6418 case tok::kw_inout:
6419 case tok::kw_out:
6420 case tok::kw_nointerpolation:
6421 case tok::kw_linear:
6422 case tok::kw_centroid:
6423 case tok::kw_noperspective:
6424 case tok::kw_sample:
6425 case tok::kw_center:
6426 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
6427 ParseHLSLQualifiers(DS.getAttributes());
6428 continue;
6429
6430 // __ptrauth qualifier.
6431 case tok::kw___ptrauth:
6432 if (!AtomicOrPtrauthAllowed)
6433 goto DoneWithTypeQuals;
6434 ParsePtrauthQualifier(DS.getAttributes());
6435 EndLoc = PrevTokLocation;
6436 continue;
6437
6438 case tok::kw___unaligned:
6439 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
6440 getLangOpts());
6441 break;
6442 case tok::kw___uptr:
6443 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
6444 // with the MS modifier keyword.
6445 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
6446 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
6447 if (TryKeywordIdentFallback(false))
6448 continue;
6449 }
6450 [[fallthrough]];
6451 case tok::kw___sptr:
6452 case tok::kw___w64:
6453 case tok::kw___ptr64:
6454 case tok::kw___ptr32:
6455 case tok::kw___cdecl:
6456 case tok::kw___stdcall:
6457 case tok::kw___fastcall:
6458 case tok::kw___thiscall:
6459 case tok::kw___regcall:
6460 case tok::kw___vectorcall:
6461 if (AttrReqs & AR_DeclspecAttributesParsed) {
6462 ParseMicrosoftTypeAttributes(DS.getAttributes());
6463 continue;
6464 }
6465 goto DoneWithTypeQuals;
6466
6467 case tok::kw___funcref:
6468 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
6469 continue;
6470
6471 case tok::kw___pascal:
6472 if (AttrReqs & AR_VendorAttributesParsed) {
6473 ParseBorlandTypeAttributes(DS.getAttributes());
6474 continue;
6475 }
6476 goto DoneWithTypeQuals;
6477
6478 // Nullability type specifiers.
6479 case tok::kw__Nonnull:
6480 case tok::kw__Nullable:
6481 case tok::kw__Nullable_result:
6482 case tok::kw__Null_unspecified:
6483 ParseNullabilityTypeSpecifiers(DS.getAttributes());
6484 continue;
6485
6486 // Objective-C 'kindof' types.
6487 case tok::kw___kindof:
6488 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc,
6489 AttributeScopeInfo(), nullptr, 0,
6490 tok::kw___kindof);
6491 (void)ConsumeToken();
6492 continue;
6493
6494 case tok::kw___attribute:
6495 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
6496 // When GNU attributes are expressly forbidden, diagnose their usage.
6497 Diag(Tok, diag::err_attributes_not_allowed);
6498
6499 // Parse the attributes even if they are rejected to ensure that error
6500 // recovery is graceful.
6501 if (AttrReqs & AR_GNUAttributesParsed ||
6502 AttrReqs & AR_GNUAttributesParsedAndRejected) {
6503 ParseGNUAttributes(DS.getAttributes(), LateAttrs);
6504 continue; // do *not* consume the next token!
6505 }
6506 // otherwise, FALL THROUGH!
6507 [[fallthrough]];
6508 default:
6509 DoneWithTypeQuals:
6510 // If this is not a type-qualifier token, we're done reading type
6511 // qualifiers. First verify that DeclSpec's are consistent.
6512 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
6513 if (EndLoc.isValid())
6514 DS.SetRangeEnd(EndLoc);
6515 return;
6516 }
6517
6518 // If the specifier combination wasn't legal, issue a diagnostic.
6519 if (isInvalid) {
6520 assert(PrevSpec && "Method did not return previous specifier!");
6521 Diag(Tok, DiagID) << PrevSpec;
6522 }
6523 EndLoc = ConsumeToken();
6524 }
6525}
6526
6527void Parser::ParseDeclarator(Declarator &D) {
6528 /// This implements the 'declarator' production in the C grammar, then checks
6529 /// for well-formedness and issues diagnostics.
6530 Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
6531 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6532 });
6533}
6534
6535static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
6536 DeclaratorContext TheContext) {
6537 if (Kind == tok::star || Kind == tok::caret)
6538 return true;
6539
6540 // OpenCL 2.0 and later define this keyword.
6541 if (Kind == tok::kw_pipe && Lang.OpenCL &&
6542 Lang.getOpenCLCompatibleVersion() >= 200)
6543 return true;
6544
6545 if (!Lang.CPlusPlus)
6546 return false;
6547
6548 if (Kind == tok::amp)
6549 return true;
6550
6551 // We parse rvalue refs in C++03, because otherwise the errors are scary.
6552 // But we must not parse them in conversion-type-ids and new-type-ids, since
6553 // those can be legitimately followed by a && operator.
6554 // (The same thing can in theory happen after a trailing-return-type, but
6555 // since those are a C++11 feature, there is no rejects-valid issue there.)
6556 if (Kind == tok::ampamp)
6557 return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId &&
6558 TheContext != DeclaratorContext::CXXNew);
6559
6560 return false;
6561}
6562
6563// Indicates whether the given declarator is a pipe declarator.
6564static bool isPipeDeclarator(const Declarator &D) {
6565 const unsigned NumTypes = D.getNumTypeObjects();
6566
6567 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
6569 return true;
6570
6571 return false;
6572}
6573
6574void Parser::ParseDeclaratorInternal(Declarator &D,
6575 DirectDeclParseFunction DirectDeclParser) {
6576 if (Diags.hasAllExtensionsSilenced())
6577 D.setExtension();
6578
6579 // C++ member pointers start with a '::' or a nested-name.
6580 // Member pointers get special handling, since there's no place for the
6581 // scope spec in the generic path below.
6582 // A 'decltype' can only begin a nested-name-specifier if it is followed by
6583 // '('; otherwise it is not a decltype-specifier at all and must not be
6584 // parsed as one.
6585 if (getLangOpts().CPlusPlus &&
6586 (Tok.is(tok::coloncolon) ||
6587 (Tok.is(tok::kw_decltype) && NextToken().is(tok::l_paren)) ||
6588 (Tok.is(tok::identifier) &&
6589 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
6590 Tok.is(tok::annot_cxxscope))) {
6591 TentativeParsingAction TPA(*this, /*Unannotated=*/true);
6592 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6594 CXXScopeSpec SS;
6596
6597 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6598 /*ObjectHasErrors=*/false,
6599 /*EnteringContext=*/false,
6600 /*MayBePseudoDestructor=*/nullptr,
6601 /*IsTypename=*/false, /*LastII=*/nullptr,
6602 /*OnlyNamespace=*/false,
6603 /*InUsingDeclaration=*/false,
6604 /*Disambiguation=*/EnteringContext,
6605 /*IsAddressOfOperand=*/false,
6606 /*IsInDeclarationContext=*/true) ||
6607
6608 SS.isEmpty() || SS.isInvalid() || !EnteringContext ||
6609 Tok.is(tok::star)) {
6610 TPA.Commit();
6611 if (SS.isNotEmpty() && Tok.is(tok::star)) {
6612 if (SS.isValid()) {
6613 checkCompoundToken(SS.getEndLoc(), tok::coloncolon,
6614 CompoundToken::MemberPtr);
6615 }
6616
6617 SourceLocation StarLoc = ConsumeToken();
6618 D.SetRangeEnd(StarLoc);
6619 DeclSpec DS(AttrFactory);
6620 ParseTypeQualifierListOpt(DS);
6621 D.ExtendWithDeclSpec(DS);
6622
6623 // Recurse to parse whatever is left.
6624 Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
6625 ParseDeclaratorInternal(D, DirectDeclParser);
6626 });
6627
6628 // Sema will have to catch (syntactically invalid) pointers into global
6629 // scope. It has to catch pointers into namespace scope anyway.
6631 SS, DS.getTypeQualifiers(), StarLoc, DS.getEndLoc()),
6632 std::move(DS.getAttributes()),
6633 /*EndLoc=*/SourceLocation());
6634 return;
6635 }
6636 } else {
6637 TPA.Revert();
6638 SS.clear();
6639 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6640 /*ObjectHasErrors=*/false,
6641 /*EnteringContext=*/true);
6642 }
6643
6644 if (SS.isNotEmpty()) {
6645 // The scope spec really belongs to the direct-declarator.
6646 if (D.mayHaveIdentifier())
6647 D.getCXXScopeSpec() = std::move(SS);
6648 else
6649 AnnotateScopeToken(SS, true);
6650
6651 if (DirectDeclParser)
6652 (this->*DirectDeclParser)(D);
6653 return;
6654 }
6655 }
6656
6657 tok::TokenKind Kind = Tok.getKind();
6658
6659 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclarator(D)) {
6660 DeclSpec DS(AttrFactory);
6661 ParseTypeQualifierListOpt(DS);
6662
6664 D.getDeclSpec().getPipeLoc()),
6665 std::move(DS.getAttributes()), SourceLocation());
6666 }
6667
6668 // Not a pointer, C++ reference, or block.
6669 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
6670 if (DirectDeclParser)
6671 (this->*DirectDeclParser)(D);
6672 return;
6673 }
6674
6675 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
6676 // '&&' -> rvalue reference
6677 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
6678 D.SetRangeEnd(Loc);
6679
6680 if (Kind == tok::star || Kind == tok::caret) {
6681 // Is a pointer.
6682 DeclSpec DS(AttrFactory);
6683
6684 // GNU attributes are not allowed here in a new-type-id, but Declspec and
6685 // C++11 attributes are allowed.
6686 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
6688 ? AR_GNUAttributesParsed
6689 : AR_GNUAttributesParsedAndRejected);
6690 ParseTypeQualifierListOpt(DS, Reqs, /*AtomicOrPtrauthAllowed=*/true,
6691 !D.mayOmitIdentifier());
6692 D.ExtendWithDeclSpec(DS);
6693
6694 // Recursively parse the declarator.
6695 Actions.runWithSufficientStackSpace(
6696 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6697 if (Kind == tok::star)
6698 // Remember that we parsed a pointer type, and remember the type-quals.
6700 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
6704 std::move(DS.getAttributes()), SourceLocation());
6705 else
6706 // Remember that we parsed a Block type, and remember the type-quals.
6707 D.AddTypeInfo(
6709 std::move(DS.getAttributes()), SourceLocation());
6710 } else {
6711 // Is a reference
6712 DeclSpec DS(AttrFactory);
6713
6714 // Complain about rvalue references in C++03, but then go on and build
6715 // the declarator.
6716 if (Kind == tok::ampamp)
6717 DiagCompat(Loc, diag_compat::rvalue_reference);
6718
6719 // GNU-style and C++11 attributes are allowed here, as is restrict.
6720 ParseTypeQualifierListOpt(DS);
6721 D.ExtendWithDeclSpec(DS);
6722
6723 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
6724 // cv-qualifiers are introduced through the use of a typedef or of a
6725 // template type argument, in which case the cv-qualifiers are ignored.
6728 Diag(DS.getConstSpecLoc(),
6729 diag::err_invalid_reference_qualifier_application) << "const";
6732 diag::err_invalid_reference_qualifier_application) << "volatile";
6733 // 'restrict' is permitted as an extension.
6736 diag::err_invalid_reference_qualifier_application) << "_Atomic";
6737 }
6738
6739 // Recursively parse the declarator.
6740 Actions.runWithSufficientStackSpace(
6741 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6742
6743 if (D.getNumTypeObjects() > 0) {
6744 // C++ [dcl.ref]p4: There shall be no references to references.
6745 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
6746 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
6747 if (const IdentifierInfo *II = D.getIdentifier())
6748 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6749 << II;
6750 else
6751 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6752 << "type name";
6753
6754 // Once we've complained about the reference-to-reference, we
6755 // can go ahead and build the (technically ill-formed)
6756 // declarator: reference collapsing will take care of it.
6757 }
6758 }
6759
6760 // Remember that we parsed a reference type.
6762 Kind == tok::amp),
6763 std::move(DS.getAttributes()), SourceLocation());
6764 }
6765}
6766
6767// When correcting from misplaced brackets before the identifier, the location
6768// is saved inside the declarator so that other diagnostic messages can use
6769// them. This extracts and returns that location, or returns the provided
6770// location if a stored location does not exist.
6772 SourceLocation Loc) {
6773 if (D.getName().StartLocation.isInvalid() &&
6775 return D.getName().EndLocation;
6776
6777 return Loc;
6778}
6779
6780void Parser::ParseDirectDeclarator(Declarator &D) {
6781 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
6782
6784 // This might be a C++17 structured binding.
6785 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
6787 return ParseDecompositionDeclarator(D);
6788
6789 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
6790 // this context it is a bitfield. Also in range-based for statement colon
6791 // may delimit for-range-declaration.
6793 *this, D.getContext() == DeclaratorContext::Member ||
6796
6797 // ParseDeclaratorInternal might already have parsed the scope.
6798 if (D.getCXXScopeSpec().isEmpty()) {
6799 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6801 ParseOptionalCXXScopeSpecifier(
6802 D.getCXXScopeSpec(), /*ObjectType=*/nullptr,
6803 /*ObjectHasErrors=*/false, EnteringContext);
6804 }
6805
6806 // C++23 [basic.scope.namespace]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 // C++23 [basic.scope.class]p1:
6811 // For each non-friend redeclaration or specialization whose target scope
6812 // is or is contained by the scope, the portion after the declarator-id,
6813 // class-head-name, or enum-head-name is also included in the scope.
6814 //
6815 // FIXME: We should not be doing this for friend declarations; they have
6816 // their own special lookup semantics specified by [basic.lookup.unqual]p6.
6817 if (D.getCXXScopeSpec().isValid()) {
6818 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
6819 D.getCXXScopeSpec()))
6820 // Change the declaration context for name lookup, until this function
6821 // is exited (and the declarator has been parsed).
6822 DeclScopeObj.EnterDeclaratorScope();
6823 else if (getObjCDeclContext()) {
6824 // Ensure that we don't interpret the next token as an identifier when
6825 // dealing with declarations in an Objective-C container.
6826 D.SetIdentifier(nullptr, Tok.getLocation());
6827 D.setInvalidType(true);
6828 ConsumeToken();
6829 goto PastIdentifier;
6830 }
6831 }
6832
6833 // C++0x [dcl.fct]p14:
6834 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
6835 // parameter-declaration-clause without a preceding comma. In this case,
6836 // the ellipsis is parsed as part of the abstract-declarator if the type
6837 // of the parameter either names a template parameter pack that has not
6838 // been expanded or contains auto; otherwise, it is parsed as part of the
6839 // parameter-declaration-clause.
6840 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
6844 NextToken().is(tok::r_paren) && !D.hasGroupingParens() &&
6845 !Actions.containsUnexpandedParameterPacks(D) &&
6847 SourceLocation EllipsisLoc = ConsumeToken();
6848 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
6849 // The ellipsis was put in the wrong place. Recover, and explain to
6850 // the user what they should have done.
6851 ParseDeclarator(D);
6852 if (EllipsisLoc.isValid())
6853 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6854 return;
6855 } else
6856 D.setEllipsisLoc(EllipsisLoc);
6857
6858 // The ellipsis can't be followed by a parenthesized declarator. We
6859 // check for that in ParseParenDeclarator, after we have disambiguated
6860 // the l_paren token.
6861 }
6862
6863 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
6864 tok::tilde)) {
6865 // We found something that indicates the start of an unqualified-id.
6866 // Parse that unqualified-id.
6867 bool AllowConstructorName;
6868 bool AllowDeductionGuide;
6869 if (D.getDeclSpec().hasTypeSpecifier()) {
6870 AllowConstructorName = false;
6871 AllowDeductionGuide = false;
6872 } else if (D.getCXXScopeSpec().isSet()) {
6873 AllowConstructorName = (D.getContext() == DeclaratorContext::File ||
6875 AllowDeductionGuide = false;
6876 } else {
6877 AllowConstructorName = (D.getContext() == DeclaratorContext::Member);
6878 AllowDeductionGuide = (D.getContext() == DeclaratorContext::File ||
6880 }
6881
6882 bool HadScope = D.getCXXScopeSpec().isValid();
6883 SourceLocation TemplateKWLoc;
6885 /*ObjectType=*/nullptr,
6886 /*ObjectHadErrors=*/false,
6887 /*EnteringContext=*/true,
6888 /*AllowDestructorName=*/true, AllowConstructorName,
6889 AllowDeductionGuide, &TemplateKWLoc,
6890 D.getName()) ||
6891 // Once we're past the identifier, if the scope was bad, mark the
6892 // whole declarator bad.
6893 D.getCXXScopeSpec().isInvalid()) {
6894 D.SetIdentifier(nullptr, Tok.getLocation());
6895 D.setInvalidType(true);
6896 } else {
6897 // ParseUnqualifiedId might have parsed a scope specifier during error
6898 // recovery. If it did so, enter that scope.
6899 if (!HadScope && D.getCXXScopeSpec().isValid() &&
6900 Actions.ShouldEnterDeclaratorScope(getCurScope(),
6901 D.getCXXScopeSpec()))
6902 DeclScopeObj.EnterDeclaratorScope();
6903
6904 // Parsed the unqualified-id; update range information and move along.
6905 if (D.getSourceRange().getBegin().isInvalid())
6908 }
6909 goto PastIdentifier;
6910 }
6911
6912 if (D.getCXXScopeSpec().isNotEmpty()) {
6913 // We have a scope specifier but no following unqualified-id.
6914 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
6915 diag::err_expected_unqualified_id)
6916 << /*C++*/1;
6917 D.SetIdentifier(nullptr, Tok.getLocation());
6918 goto PastIdentifier;
6919 }
6920 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
6921 assert(!getLangOpts().CPlusPlus &&
6922 "There's a C++-specific check for tok::identifier above");
6923 assert(Tok.getIdentifierInfo() && "Not an identifier?");
6924 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
6925 D.SetRangeEnd(Tok.getLocation());
6926 ConsumeToken();
6927 goto PastIdentifier;
6928 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
6929 // We're not allowed an identifier here, but we got one. Try to figure out
6930 // if the user was trying to attach a name to the type, or whether the name
6931 // is some unrelated trailing syntax.
6932 bool DiagnoseIdentifier = false;
6933 if (D.hasGroupingParens())
6934 // An identifier within parens is unlikely to be intended to be anything
6935 // other than a name being "declared".
6936 DiagnoseIdentifier = true;
6938 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
6939 DiagnoseIdentifier =
6940 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
6941 else if (D.getContext() == DeclaratorContext::AliasDecl ||
6943 // The most likely error is that the ';' was forgotten.
6944 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
6947 !isCXX11VirtSpecifier(Tok))
6948 DiagnoseIdentifier = NextToken().isOneOf(
6949 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
6950 if (DiagnoseIdentifier) {
6951 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
6952 << FixItHint::CreateRemoval(Tok.getLocation());
6953 D.SetIdentifier(nullptr, Tok.getLocation());
6954 ConsumeToken();
6955 goto PastIdentifier;
6956 }
6957 }
6958
6959 if (Tok.is(tok::l_paren)) {
6960 // If this might be an abstract-declarator followed by a direct-initializer,
6961 // check whether this is a valid declarator chunk. If it can't be, assume
6962 // that it's an initializer instead.
6964 RevertingTentativeParsingAction PA(*this);
6965 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true,
6967 TPResult::False) {
6968 D.SetIdentifier(nullptr, Tok.getLocation());
6969 goto PastIdentifier;
6970 }
6971 }
6972
6973 // direct-declarator: '(' declarator ')'
6974 // direct-declarator: '(' attributes declarator ')'
6975 // Example: 'char (*X)' or 'int (*XX)(void)'
6976 ParseParenDeclarator(D);
6977
6978 // As noted above, a structured binding declarator cannot be followed by any
6979 // declarator chunks.
6981 return;
6982
6983 // If the declarator was parenthesized, we entered the declarator
6984 // scope when parsing the parenthesized declarator, then exited
6985 // the scope already. Re-enter the scope, if we need to.
6986 if (D.getCXXScopeSpec().isSet()) {
6987 // If there was an error parsing parenthesized declarator, declarator
6988 // scope may have been entered before. Don't do it again.
6989 if (!D.isInvalidType() &&
6990 Actions.ShouldEnterDeclaratorScope(getCurScope(),
6991 D.getCXXScopeSpec()))
6992 // Change the declaration context for name lookup, until this function
6993 // is exited (and the declarator has been parsed).
6994 DeclScopeObj.EnterDeclaratorScope();
6995 }
6996 } else if (D.mayOmitIdentifier()) {
6997 // This could be something simple like "int" (in which case the declarator
6998 // portion is empty), if an abstract-declarator is allowed.
6999 D.SetIdentifier(nullptr, Tok.getLocation());
7000
7001 // The grammar for abstract-pack-declarator does not allow grouping parens.
7002 // FIXME: Revisit this once core issue 1488 is resolved.
7003 if (D.hasEllipsis() && D.hasGroupingParens())
7004 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
7005 diag::ext_abstract_pack_declarator_parens);
7006 } else {
7007 if (Tok.getKind() == tok::annot_pragma_parser_crash)
7008 LLVM_BUILTIN_TRAP;
7009 if (Tok.is(tok::l_square))
7010 return ParseMisplacedBracketDeclarator(D);
7012 // Objective-C++: Detect C++ keywords and try to prevent further errors by
7013 // treating these keyword as valid member names.
7015 !Tok.isAnnotation() && Tok.getIdentifierInfo() &&
7016 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
7017 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
7018 diag::err_expected_member_name_or_semi_objcxx_keyword)
7019 << Tok.getIdentifierInfo()
7020 << (D.getDeclSpec().isEmpty() ? SourceRange()
7021 : D.getDeclSpec().getSourceRange());
7022 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
7023 D.SetRangeEnd(Tok.getLocation());
7024 ConsumeToken();
7025 goto PastIdentifier;
7026 }
7027 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
7028 diag::err_expected_member_name_or_semi)
7029 << (D.getDeclSpec().isEmpty() ? SourceRange()
7030 : D.getDeclSpec().getSourceRange());
7031 } else {
7032 if (Tok.getKind() == tok::TokenKind::kw_while) {
7033 Diag(Tok, diag::err_while_loop_outside_of_a_function);
7034 } else if (getLangOpts().CPlusPlus) {
7035 if (Tok.isOneOf(tok::period, tok::arrow))
7036 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
7037 else {
7038 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
7039 if (Tok.isAtStartOfLine() && Loc.isValid())
7040 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
7041 << getLangOpts().CPlusPlus;
7042 else
7043 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
7044 diag::err_expected_unqualified_id)
7045 << getLangOpts().CPlusPlus;
7046 }
7047 } else {
7048 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
7049 diag::err_expected_either)
7050 << tok::identifier << tok::l_paren;
7051 }
7052 }
7053 D.SetIdentifier(nullptr, Tok.getLocation());
7054 D.setInvalidType(true);
7055 }
7056
7057 PastIdentifier:
7058 assert(D.isPastIdentifier() &&
7059 "Haven't past the location of the identifier yet?");
7060
7061 // Don't parse attributes unless we have parsed an unparenthesized name.
7062 if (D.hasName() && !D.getNumTypeObjects())
7063 MaybeParseCXX11Attributes(D);
7064
7065 while (true) {
7066 if (Tok.is(tok::l_paren)) {
7067 bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
7068 // Enter function-declaration scope, limiting any declarators to the
7069 // function prototype scope, including parameter declarators.
7070 ParseScope PrototypeScope(
7072 (IsFunctionDeclaration ? Scope::FunctionDeclarationScope
7073 : Scope::NoScope));
7074
7075 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
7076 // In such a case, check if we actually have a function declarator; if it
7077 // is not, the declarator has been fully parsed.
7078 bool IsAmbiguous = false;
7080 // C++2a [temp.res]p5
7081 // A qualified-id is assumed to name a type if
7082 // - [...]
7083 // - it is a decl-specifier of the decl-specifier-seq of a
7084 // - [...]
7085 // - parameter-declaration in a member-declaration [...]
7086 // - parameter-declaration in a declarator of a function or function
7087 // template declaration whose declarator-id is qualified [...]
7088 auto AllowImplicitTypename = ImplicitTypenameContext::No;
7089 if (D.getCXXScopeSpec().isSet())
7090 AllowImplicitTypename =
7091 (ImplicitTypenameContext)Actions.isDeclaratorFunctionLike(D);
7092 else if (D.getContext() == DeclaratorContext::Member) {
7093 AllowImplicitTypename = ImplicitTypenameContext::Yes;
7094 }
7095
7096 // The name of the declarator, if any, is tentatively declared within
7097 // a possible direct initializer.
7098 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
7099 bool IsFunctionDecl =
7100 isCXXFunctionDeclarator(&IsAmbiguous, AllowImplicitTypename);
7101 TentativelyDeclaredIdentifiers.pop_back();
7102 if (!IsFunctionDecl)
7103 break;
7104 }
7105 ParsedAttributes attrs(AttrFactory);
7106 BalancedDelimiterTracker T(*this, tok::l_paren);
7107 T.consumeOpen();
7108 if (IsFunctionDeclaration)
7109 Actions.ActOnStartFunctionDeclarationDeclarator(D,
7110 TemplateParameterDepth);
7111 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
7112 if (IsFunctionDeclaration)
7113 Actions.ActOnFinishFunctionDeclarationDeclarator(D);
7114 PrototypeScope.Exit();
7115 } else if (Tok.is(tok::l_square)) {
7116 ParseBracketDeclarator(D);
7117 } else if (Tok.isRegularKeywordAttribute()) {
7118 // For consistency with attribute parsing.
7119 Diag(Tok, diag::err_keyword_not_allowed) << Tok.getIdentifierInfo();
7120 bool TakesArgs = doesKeywordAttributeTakeArgs(Tok.getKind());
7121 ConsumeToken();
7122 if (TakesArgs) {
7123 BalancedDelimiterTracker T(*this, tok::l_paren);
7124 if (!T.consumeOpen())
7125 T.skipToEnd();
7126 }
7127 } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
7128 // This declarator is declaring a function, but the requires clause is
7129 // in the wrong place:
7130 // void (f() requires true);
7131 // instead of
7132 // void f() requires true;
7133 // or
7134 // void (f()) requires true;
7135 Diag(Tok, diag::err_requires_clause_inside_parens);
7136 ConsumeToken();
7137 ExprResult TrailingRequiresClause =
7138 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
7139 if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
7141 // We're already ill-formed if we got here but we'll accept it anyway.
7142 D.setTrailingRequiresClause(TrailingRequiresClause.get());
7143 } else {
7144 break;
7145 }
7146 }
7147}
7148
7149void Parser::ParseDecompositionDeclarator(Declarator &D) {
7150 assert(Tok.is(tok::l_square));
7151
7152 TentativeParsingAction PA(*this);
7153 BalancedDelimiterTracker T(*this, tok::l_square);
7154 T.consumeOpen();
7155
7156 if (isCXX11AttributeSpecifier() != CXX11AttributeKind::NotAttributeSpecifier)
7157 DiagnoseAndSkipCXX11Attributes();
7158
7159 // If this doesn't look like a structured binding, maybe it's a misplaced
7160 // array declarator.
7161 if (!(Tok.isOneOf(tok::identifier, tok::ellipsis) &&
7162 NextToken().isOneOf(tok::comma, tok::r_square, tok::kw_alignas,
7163 tok::identifier, tok::l_square, tok::ellipsis)) &&
7164 !(Tok.is(tok::r_square) &&
7165 NextToken().isOneOf(tok::equal, tok::l_brace))) {
7166 PA.Revert();
7167 return ParseMisplacedBracketDeclarator(D);
7168 }
7169
7170 SourceLocation PrevEllipsisLoc;
7171 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
7172 while (Tok.isNot(tok::r_square)) {
7173 if (!Bindings.empty()) {
7174 if (Tok.is(tok::comma))
7175 ConsumeToken();
7176 else {
7177 if (Tok.is(tok::identifier)) {
7178 SourceLocation EndLoc = getEndOfPreviousToken();
7179 Diag(EndLoc, diag::err_expected)
7180 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
7181 } else {
7182 Diag(Tok, diag::err_expected_comma_or_rsquare);
7183 }
7184
7185 SkipUntil({tok::r_square, tok::comma, tok::identifier, tok::ellipsis},
7187 if (Tok.is(tok::comma))
7188 ConsumeToken();
7189 else if (Tok.is(tok::r_square))
7190 break;
7191 }
7192 }
7193
7194 if (isCXX11AttributeSpecifier() !=
7196 DiagnoseAndSkipCXX11Attributes();
7197
7198 SourceLocation EllipsisLoc;
7199
7200 if (Tok.is(tok::ellipsis)) {
7201 DiagCompat(Tok, diag_compat::binding_pack);
7202 if (PrevEllipsisLoc.isValid()) {
7203 Diag(Tok, diag::err_binding_multiple_ellipses);
7204 Diag(PrevEllipsisLoc, diag::note_previous_ellipsis);
7205 break;
7206 }
7207 EllipsisLoc = Tok.getLocation();
7208 PrevEllipsisLoc = EllipsisLoc;
7209 ConsumeToken();
7210 }
7211
7212 if (Tok.isNot(tok::identifier)) {
7213 Diag(Tok, diag::err_expected) << tok::identifier;
7214 break;
7215 }
7216
7217 IdentifierInfo *II = Tok.getIdentifierInfo();
7218 SourceLocation Loc = Tok.getLocation();
7219 ConsumeToken();
7220
7221 if (Tok.is(tok::ellipsis) && !PrevEllipsisLoc.isValid()) {
7222 DiagnoseMisplacedEllipsis(Tok.getLocation(), Loc, EllipsisLoc.isValid(),
7223 true);
7224 EllipsisLoc = Tok.getLocation();
7225 ConsumeToken();
7226 }
7227
7228 ParsedAttributes Attrs(AttrFactory);
7229 if (isCXX11AttributeSpecifier() !=
7231 DiagCompat(Tok, diag_compat::attrs_on_binding);
7232 MaybeParseCXX11Attributes(Attrs);
7233 }
7234
7235 Bindings.push_back({II, Loc, std::move(Attrs), EllipsisLoc});
7236 }
7237
7238 if (Tok.isNot(tok::r_square))
7239 // We've already diagnosed a problem here.
7240 T.skipToEnd();
7241 else {
7242 // C++17 does not allow the identifier-list in a structured binding
7243 // to be empty.
7244 if (Bindings.empty())
7245 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
7246
7247 T.consumeClose();
7248 }
7249
7250 PA.Commit();
7251
7252 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
7253 T.getCloseLocation());
7254}
7255
7256void Parser::ParseParenDeclarator(Declarator &D) {
7257 BalancedDelimiterTracker T(*this, tok::l_paren);
7258 T.consumeOpen();
7259
7260 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
7261
7262 // Eat any attributes before we look at whether this is a grouping or function
7263 // declarator paren. If this is a grouping paren, the attribute applies to
7264 // the type being built up, for example:
7265 // int (__attribute__(()) *x)(long y)
7266 // If this ends up not being a grouping paren, the attribute applies to the
7267 // first argument, for example:
7268 // int (__attribute__(()) int x)
7269 // In either case, we need to eat any attributes to be able to determine what
7270 // sort of paren this is.
7271 //
7272 ParsedAttributes attrs(AttrFactory);
7273 bool RequiresArg = false;
7274 if (Tok.is(tok::kw___attribute)) {
7275 ParseGNUAttributes(attrs);
7276
7277 // We require that the argument list (if this is a non-grouping paren) be
7278 // present even if the attribute list was empty.
7279 RequiresArg = true;
7280 }
7281
7282 // Eat any Microsoft extensions.
7283 ParseMicrosoftTypeAttributes(attrs);
7284
7285 // Eat any Borland extensions.
7286 if (Tok.is(tok::kw___pascal))
7287 ParseBorlandTypeAttributes(attrs);
7288
7289 // If we haven't past the identifier yet (or where the identifier would be
7290 // stored, if this is an abstract declarator), then this is probably just
7291 // grouping parens. However, if this could be an abstract-declarator, then
7292 // this could also be the start of function arguments (consider 'void()').
7293 bool isGrouping;
7294
7295 if (!D.mayOmitIdentifier()) {
7296 // If this can't be an abstract-declarator, this *must* be a grouping
7297 // paren, because we haven't seen the identifier yet.
7298 isGrouping = true;
7299 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
7301 Tok.is(tok::ellipsis) &&
7302 NextToken().is(tok::r_paren)) || // C++ int(...)
7303 isDeclarationSpecifier(
7304 ImplicitTypenameContext::No) || // 'int(int)' is a function.
7305 isCXX11AttributeSpecifier() !=
7307 // is a function.
7308 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
7309 // considered to be a type, not a K&R identifier-list.
7310 isGrouping = false;
7311 } else {
7312 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
7313 isGrouping = true;
7314 }
7315
7316 // If this is a grouping paren, handle:
7317 // direct-declarator: '(' declarator ')'
7318 // direct-declarator: '(' attributes declarator ')'
7319 if (isGrouping) {
7320 SourceLocation EllipsisLoc = D.getEllipsisLoc();
7321 D.setEllipsisLoc(SourceLocation());
7322
7323 bool hadGroupingParens = D.hasGroupingParens();
7324 D.setGroupingParens(true);
7325 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
7326 // Match the ')'.
7327 T.consumeClose();
7328 D.AddTypeInfo(
7329 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
7330 std::move(attrs), T.getCloseLocation());
7331
7332 D.setGroupingParens(hadGroupingParens);
7333
7334 // An ellipsis cannot be placed outside parentheses.
7335 if (EllipsisLoc.isValid())
7336 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
7337
7338 return;
7339 }
7340
7341 // Okay, if this wasn't a grouping paren, it must be the start of a function
7342 // argument list. Recognize that this declarator will never have an
7343 // identifier (and remember where it would have been), then call into
7344 // ParseFunctionDeclarator to handle of argument list.
7345 D.SetIdentifier(nullptr, Tok.getLocation());
7346
7347 // Enter function-declaration scope, limiting any declarators to the
7348 // function prototype scope, including parameter declarators.
7349 ParseScope PrototypeScope(this,
7353 : Scope::NoScope));
7354 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
7355 PrototypeScope.Exit();
7356}
7357
7358void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
7359 const Declarator &D, const DeclSpec &DS,
7360 std::optional<Sema::CXXThisScopeRAII> &ThisScope) {
7361 // C++11 [expr.prim.general]p3:
7362 // If a declaration declares a member function or member function
7363 // template of a class X, the expression this is a prvalue of type
7364 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
7365 // and the end of the function-definition, member-declarator, or
7366 // declarator.
7367 // FIXME: currently, "static" case isn't handled correctly.
7368 bool IsCXX11MemberFunction =
7369 getLangOpts().CPlusPlus11 &&
7374 D.getCXXScopeSpec().isValid() &&
7375 Actions.CurContext->isRecord());
7376 if (!IsCXX11MemberFunction)
7377 return;
7378
7379 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
7381 Q.addConst();
7382 // FIXME: Collect C++ address spaces.
7383 // If there are multiple different address spaces, the source is invalid.
7384 // Carry on using the first addr space for the qualifiers of 'this'.
7385 // The diagnostic will be given later while creating the function
7386 // prototype for the method.
7387 if (getLangOpts().OpenCLCPlusPlus) {
7388 for (ParsedAttr &attr : DS.getAttributes()) {
7389 LangAS ASIdx = attr.asOpenCLLangAS();
7390 if (ASIdx != LangAS::Default) {
7391 Q.addAddressSpace(ASIdx);
7392 break;
7393 }
7394 }
7395 }
7396 ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
7397 IsCXX11MemberFunction);
7398}
7399
7400void Parser::ParseFunctionDeclarator(Declarator &D,
7401 ParsedAttributes &FirstArgAttrs,
7402 BalancedDelimiterTracker &Tracker,
7403 bool IsAmbiguous,
7404 bool RequiresArg) {
7405 assert(getCurScope()->isFunctionPrototypeScope() &&
7406 "Should call from a Function scope");
7407 // lparen is already consumed!
7408 assert(D.isPastIdentifier() && "Should not call before identifier!");
7409
7410 // This should be true when the function has typed arguments.
7411 // Otherwise, it is treated as a K&R-style function.
7412 bool HasProto = false;
7413 // Build up an array of information about the parsed arguments.
7414 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
7415 // Remember where we see an ellipsis, if any.
7416 SourceLocation EllipsisLoc;
7417
7418 DeclSpec DS(AttrFactory);
7419 bool RefQualifierIsLValueRef = true;
7420 SourceLocation RefQualifierLoc;
7422 SourceRange ESpecRange;
7423 SmallVector<ParsedType, 2> DynamicExceptions;
7424 SmallVector<SourceRange, 2> DynamicExceptionRanges;
7425 ExprResult NoexceptExpr;
7426 CachedTokens *ExceptionSpecTokens = nullptr;
7427 ParsedAttributes FnAttrs(AttrFactory);
7429 SourceLocation TrailingReturnTypeLoc;
7430
7431 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
7432 EndLoc is the end location for the function declarator.
7433 They differ for trailing return types. */
7434 SourceLocation StartLoc, LocalEndLoc, EndLoc;
7435 SourceLocation LParenLoc, RParenLoc;
7436 LParenLoc = Tracker.getOpenLocation();
7437 StartLoc = LParenLoc;
7438
7439 if (isFunctionDeclaratorIdentifierList()) {
7440 if (RequiresArg)
7441 Diag(Tok, diag::err_argument_required_after_attribute);
7442
7443 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
7444
7445 Tracker.consumeClose();
7446 RParenLoc = Tracker.getCloseLocation();
7447 LocalEndLoc = RParenLoc;
7448 EndLoc = RParenLoc;
7449
7450 // If there are attributes following the identifier list, parse them and
7451 // prohibit them.
7452 MaybeParseCXX11Attributes(FnAttrs);
7453 ProhibitAttributes(FnAttrs);
7454 } else {
7455 if (Tok.isNot(tok::r_paren))
7456 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
7457 else if (RequiresArg)
7458 Diag(Tok, diag::err_argument_required_after_attribute);
7459
7460 // OpenCL disallows functions without a prototype, but it doesn't enforce
7461 // strict prototypes as in C23 because it allows a function definition to
7462 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
7463 HasProto = ParamInfo.size() || getLangOpts().requiresStrictPrototypes() ||
7464 getLangOpts().OpenCL;
7465
7466 // If we have the closing ')', eat it.
7467 Tracker.consumeClose();
7468 RParenLoc = Tracker.getCloseLocation();
7469 LocalEndLoc = RParenLoc;
7470 EndLoc = RParenLoc;
7471
7472 if (getLangOpts().CPlusPlus) {
7473 // FIXME: Accept these components in any order, and produce fixits to
7474 // correct the order if the user gets it wrong. Ideally we should deal
7475 // with the pure-specifier in the same way.
7476
7477 // Parse cv-qualifier-seq[opt].
7478 ParseTypeQualifierListOpt(
7479 DS, AR_NoAttributesParsed,
7480 /*AtomicOrPtrauthAllowed=*/false,
7481 /*IdentifierRequired=*/false, [&]() {
7482 Actions.CodeCompletion().CodeCompleteFunctionQualifiers(DS, D);
7483 });
7484 if (!DS.getSourceRange().getEnd().isInvalid()) {
7485 EndLoc = DS.getSourceRange().getEnd();
7486 }
7487
7488 // Parse ref-qualifier[opt].
7489 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
7490 EndLoc = RefQualifierLoc;
7491
7492 std::optional<Sema::CXXThisScopeRAII> ThisScope;
7493 InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
7494
7495 // C++ [class.mem.general]p8:
7496 // A complete-class context of a class (template) is a
7497 // - function body,
7498 // - default argument,
7499 // - default template argument,
7500 // - noexcept-specifier, or
7501 // - default member initializer
7502 // within the member-specification of the class or class template.
7503 //
7504 // Parse exception-specification[opt]. If we are in the
7505 // member-specification of a class or class template, this is a
7506 // complete-class context and parsing of the noexcept-specifier should be
7507 // delayed (even if this is a friend declaration).
7508 bool Delayed = D.getContext() == DeclaratorContext::Member &&
7510 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
7511 GetLookAheadToken(0).is(tok::kw_noexcept) &&
7512 GetLookAheadToken(1).is(tok::l_paren) &&
7513 GetLookAheadToken(2).is(tok::kw_noexcept) &&
7514 GetLookAheadToken(3).is(tok::l_paren) &&
7515 GetLookAheadToken(4).is(tok::identifier) &&
7516 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
7517 // HACK: We've got an exception-specification
7518 // noexcept(noexcept(swap(...)))
7519 // or
7520 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
7521 // on a 'swap' member function. This is a libstdc++ bug; the lookup
7522 // for 'swap' will only find the function we're currently declaring,
7523 // whereas it expects to find a non-member swap through ADL. Turn off
7524 // delayed parsing to give it a chance to find what it expects.
7525 Delayed = false;
7526 }
7527 ESpecType = tryParseExceptionSpecification(Delayed,
7528 ESpecRange,
7529 DynamicExceptions,
7530 DynamicExceptionRanges,
7531 NoexceptExpr,
7532 ExceptionSpecTokens);
7533 if (ESpecType != EST_None)
7534 EndLoc = ESpecRange.getEnd();
7535
7536 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
7537 // after the exception-specification.
7538 MaybeParseCXX11Attributes(FnAttrs);
7539
7540 // Parse trailing-return-type[opt].
7541 LocalEndLoc = EndLoc;
7542 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
7543 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
7545 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
7546 LocalEndLoc = Tok.getLocation();
7547 SourceRange Range;
7549 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
7550 TrailingReturnTypeLoc = Range.getBegin();
7551 EndLoc = Range.getEnd();
7552 }
7553 } else {
7554 MaybeParseCXX11Attributes(FnAttrs);
7555 }
7556 }
7557
7558 // Collect non-parameter declarations from the prototype if this is a function
7559 // declaration. They will be moved into the scope of the function. Only do
7560 // this in C and not C++, where the decls will continue to live in the
7561 // surrounding context.
7562 SmallVector<NamedDecl *, 0> DeclsInPrototype;
7563 if (getCurScope()->isFunctionDeclarationScope() && !getLangOpts().CPlusPlus) {
7564 for (Decl *D : getCurScope()->decls()) {
7565 NamedDecl *ND = dyn_cast<NamedDecl>(D);
7566 if (!ND || isa<ParmVarDecl>(ND))
7567 continue;
7568 DeclsInPrototype.push_back(ND);
7569 }
7570 // Sort DeclsInPrototype based on raw encoding of the source location.
7571 // Scope::decls() is iterating over a SmallPtrSet so sort the Decls before
7572 // moving to DeclContext. This provides a stable ordering for traversing
7573 // Decls in DeclContext, which is important for tasks like ASTWriter for
7574 // deterministic output.
7575 llvm::sort(DeclsInPrototype, [](Decl *D1, Decl *D2) {
7576 return D1->getLocation().getRawEncoding() <
7578 });
7579 }
7580
7581 // Remember that we parsed a function type, and remember the attributes.
7583 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
7584 ParamInfo.size(), EllipsisLoc, RParenLoc,
7585 RefQualifierIsLValueRef, RefQualifierLoc,
7586 /*MutableLoc=*/SourceLocation(),
7587 ESpecType, ESpecRange, DynamicExceptions.data(),
7588 DynamicExceptionRanges.data(), DynamicExceptions.size(),
7589 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
7590 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
7591 LocalEndLoc, D, TrailingReturnType, TrailingReturnTypeLoc,
7592 &DS),
7593 std::move(FnAttrs), EndLoc);
7594}
7595
7596bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
7597 SourceLocation &RefQualifierLoc) {
7598 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
7599 DiagCompat(Tok, diag_compat::ref_qualifier);
7600 RefQualifierIsLValueRef = Tok.is(tok::amp);
7601 RefQualifierLoc = ConsumeToken();
7602 return true;
7603 }
7604 return false;
7605}
7606
7607bool Parser::isFunctionDeclaratorIdentifierList() {
7609 && Tok.is(tok::identifier)
7610 && !TryAltiVecVectorToken()
7611 // K&R identifier lists can't have typedefs as identifiers, per C99
7612 // 6.7.5.3p11.
7613 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
7614 // Identifier lists follow a really simple grammar: the identifiers can
7615 // be followed *only* by a ", identifier" or ")". However, K&R
7616 // identifier lists are really rare in the brave new modern world, and
7617 // it is very common for someone to typo a type in a non-K&R style
7618 // list. If we are presented with something like: "void foo(intptr x,
7619 // float y)", we don't want to start parsing the function declarator as
7620 // though it is a K&R style declarator just because intptr is an
7621 // invalid type.
7622 //
7623 // To handle this, we check to see if the token after the first
7624 // identifier is a "," or ")". Only then do we parse it as an
7625 // identifier list.
7626 && (!Tok.is(tok::eof) &&
7627 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
7628}
7629
7630void Parser::ParseFunctionDeclaratorIdentifierList(
7631 Declarator &D,
7633 // We should never reach this point in C23 or C++.
7634 assert(!getLangOpts().requiresStrictPrototypes() &&
7635 "Cannot parse an identifier list in C23 or C++");
7636
7637 // If there was no identifier specified for the declarator, either we are in
7638 // an abstract-declarator, or we are in a parameter declarator which was found
7639 // to be abstract. In abstract-declarators, identifier lists are not valid:
7640 // diagnose this.
7641 if (!D.getIdentifier())
7642 Diag(Tok, diag::ext_ident_list_in_param);
7643
7644 // Maintain an efficient lookup of params we have seen so far.
7645 llvm::SmallPtrSet<const IdentifierInfo *, 16> ParamsSoFar;
7646
7647 do {
7648 // If this isn't an identifier, report the error and skip until ')'.
7649 if (Tok.isNot(tok::identifier)) {
7650 Diag(Tok, diag::err_expected) << tok::identifier;
7651 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
7652 // Forget we parsed anything.
7653 ParamInfo.clear();
7654 return;
7655 }
7656
7657 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
7658
7659 // Reject 'typedef int y; int test(x, y)', but continue parsing.
7660 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
7661 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
7662
7663 // Verify that the argument identifier has not already been mentioned.
7664 if (!ParamsSoFar.insert(ParmII).second) {
7665 Diag(Tok, diag::err_param_redefinition) << ParmII;
7666 } else {
7667 // Remember this identifier in ParamInfo.
7668 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7669 Tok.getLocation(),
7670 nullptr));
7671 }
7672
7673 // Eat the identifier.
7674 ConsumeToken();
7675 // The list continues if we see a comma.
7676 } while (TryConsumeToken(tok::comma));
7677}
7678
7679void Parser::ParseParameterDeclarationClause(
7680 DeclaratorContext DeclaratorCtx, ParsedAttributes &FirstArgAttrs,
7682 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration) {
7683
7684 // Avoid exceeding the maximum function scope depth.
7685 // See https://bugs.llvm.org/show_bug.cgi?id=19607
7686 // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
7687 // getFunctionPrototypeDepth() - 1.
7688 if (getCurScope()->getFunctionPrototypeDepth() - 1 >
7690 Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
7692 cutOffParsing();
7693 return;
7694 }
7695
7696 // C++2a [temp.res]p5
7697 // A qualified-id is assumed to name a type if
7698 // - [...]
7699 // - it is a decl-specifier of the decl-specifier-seq of a
7700 // - [...]
7701 // - parameter-declaration in a member-declaration [...]
7702 // - parameter-declaration in a declarator of a function or function
7703 // template declaration whose declarator-id is qualified [...]
7704 // - parameter-declaration in a lambda-declarator [...]
7705 auto AllowImplicitTypename = ImplicitTypenameContext::No;
7706 if (DeclaratorCtx == DeclaratorContext::Member ||
7707 DeclaratorCtx == DeclaratorContext::LambdaExpr ||
7708 DeclaratorCtx == DeclaratorContext::RequiresExpr ||
7709 IsACXXFunctionDeclaration) {
7710 AllowImplicitTypename = ImplicitTypenameContext::Yes;
7711 }
7712
7713 // An attribute on a parameter may name another parameter of the same
7714 // prototype that is declared later, such as a callback parameter whose
7715 // attribute names a lock passed after it. Defer those to the end of the
7716 // clause, where every parameter is declared and the prototype scope is still
7717 // open, so no scope need be re-entered.
7718 LateParsedAttrList LateParamAttrs(/*PSoon=*/true,
7719 /*LateAttrParseExperimentalExtOnly=*/true);
7720
7721 do {
7722 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
7723 // before deciding this was a parameter-declaration-clause.
7724 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
7725 break;
7726
7727 // Parse the declaration-specifiers.
7728 // Just use the ParsingDeclaration "scope" of the declarator.
7729 DeclSpec DS(AttrFactory);
7730
7731 ParsedAttributes ArgDeclAttrs(AttrFactory);
7732 ParsedAttributes ArgDeclSpecAttrs(AttrFactory);
7733
7734 if (FirstArgAttrs.Range.isValid()) {
7735 // If the caller parsed attributes for the first argument, add them now.
7736 // Take them so that we only apply the attributes to the first parameter.
7737 // We have already started parsing the decl-specifier sequence, so don't
7738 // parse any parameter-declaration pieces that precede it.
7739 ArgDeclSpecAttrs.takeAllPrependingFrom(FirstArgAttrs);
7740 } else {
7741 // Parse any C++11 attributes.
7742 MaybeParseCXX11Attributes(ArgDeclAttrs);
7743
7744 // Skip any Microsoft attributes before a param.
7745 MaybeParseMicrosoftAttributes(ArgDeclSpecAttrs);
7746 }
7747
7748 SourceLocation DSStart = Tok.getLocation();
7749
7750 // Parse a C++23 Explicit Object Parameter
7751 // We do that in all language modes to produce a better diagnostic.
7752 SourceLocation ThisLoc;
7753 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_this))
7754 ThisLoc = ConsumeToken();
7755
7756 ParsedTemplateInfo TemplateInfo;
7757 ParseDeclarationSpecifiers(DS, TemplateInfo, AS_none,
7758 DeclSpecContext::DSC_normal,
7759 /*LateAttrs=*/nullptr, AllowImplicitTypename);
7760
7761 DS.takeAttributesAppendingingFrom(ArgDeclSpecAttrs);
7762
7763 // Parse the declarator. This is "PrototypeContext" or
7764 // "LambdaExprParameterContext", because we must accept either
7765 // 'declarator' or 'abstract-declarator' here.
7766 Declarator ParmDeclarator(DS, ArgDeclAttrs,
7767 DeclaratorCtx == DeclaratorContext::RequiresExpr
7769 : DeclaratorCtx == DeclaratorContext::LambdaExpr
7772 ParseDeclarator(ParmDeclarator);
7773
7774 if (ThisLoc.isValid())
7775 ParmDeclarator.SetRangeBegin(ThisLoc);
7776
7777 // Parse GNU attributes, if present.
7778 MaybeParseGNUAttributes(ParmDeclarator, &LateParamAttrs);
7779 if (getLangOpts().HLSL)
7780 MaybeParseHLSLAnnotations(DS.getAttributes());
7781
7782 if (Tok.is(tok::kw_requires)) {
7783 // User tried to define a requires clause in a parameter declaration,
7784 // which is surely not a function declaration.
7785 // void f(int (*g)(int, int) requires true);
7786 Diag(Tok,
7787 diag::err_requires_clause_on_declarator_not_declaring_a_function);
7788 ConsumeToken();
7789 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
7790 }
7791
7792 // Remember this parsed parameter in ParamInfo.
7793 const IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
7794
7795 // DefArgToks is used when the parsing of default arguments needs
7796 // to be delayed.
7797 std::unique_ptr<CachedTokens> DefArgToks;
7798
7799 // If no parameter was specified, verify that *something* was specified,
7800 // otherwise we have a missing type and identifier.
7801 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
7802 ParmDeclarator.getNumTypeObjects() == 0) {
7803 // Completely missing, emit error.
7804 Diag(DSStart, diag::err_missing_param);
7805 } else {
7806 // Otherwise, we have something. Add it and let semantic analysis try
7807 // to grok it and add the result to the ParamInfo we are building.
7808
7809 // Last chance to recover from a misplaced ellipsis in an attempted
7810 // parameter pack declaration.
7811 if (Tok.is(tok::ellipsis) &&
7812 (NextToken().isNot(tok::r_paren) ||
7813 (!ParmDeclarator.getEllipsisLoc().isValid() &&
7814 !Actions.isUnexpandedParameterPackPermitted())) &&
7815 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
7816 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
7817
7818 // Now we are at the point where declarator parsing is finished.
7819 //
7820 // Try to catch keywords in place of the identifier in a declarator, and
7821 // in particular the common case where:
7822 // 1 identifier comes at the end of the declarator
7823 // 2 if the identifier is dropped, the declarator is valid but anonymous
7824 // (no identifier)
7825 // 3 declarator parsing succeeds, and then we have a trailing keyword,
7826 // which is never valid in a param list (e.g. missing a ',')
7827 // And we can't handle this in ParseDeclarator because in general keywords
7828 // may be allowed to follow the declarator. (And in some cases there'd be
7829 // better recovery like inserting punctuation). ParseDeclarator is just
7830 // treating this as an anonymous parameter, and fortunately at this point
7831 // we've already almost done that.
7832 //
7833 // We care about case 1) where the declarator type should be known, and
7834 // the identifier should be null.
7835 if (!ParmDeclarator.isInvalidType() && !ParmDeclarator.hasName() &&
7836 Tok.isNot(tok::raw_identifier) && !Tok.isAnnotation() &&
7837 Tok.getIdentifierInfo() &&
7838 Tok.getIdentifierInfo()->isKeyword(getLangOpts())) {
7839 Diag(Tok, diag::err_keyword_as_parameter) << PP.getSpelling(Tok);
7840 // Consume the keyword.
7841 ConsumeToken();
7842 }
7843
7844 // We can only store so many parameters
7845 // Skip until the the end of the parameter list, ignoring
7846 // parameters that would overflow.
7847 if (ParamInfo.size() == Type::FunctionTypeNumParamsLimit) {
7848 Diag(ParmDeclarator.getBeginLoc(),
7849 diag::err_function_parameter_limit_exceeded);
7851 break;
7852 }
7853
7854 // Inform the actions module about the parameter declarator, so it gets
7855 // added to the current scope.
7856 Decl *Param =
7857 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator, ThisLoc);
7858 // Claim deferred attributes now, before the next parameter can.
7859 DistributeCLateParsedAttrs(Param, &LateParamAttrs);
7860 // Parse the default argument, if any. We parse the default
7861 // arguments in all dialects; the semantic analysis in
7862 // ActOnParamDefaultArgument will reject the default argument in
7863 // C.
7864 if (Tok.is(tok::equal)) {
7865 SourceLocation EqualLoc = Tok.getLocation();
7866
7867 // Parse the default argument
7868 if (DeclaratorCtx == DeclaratorContext::Member) {
7869 // If we're inside a class definition, cache the tokens
7870 // corresponding to the default argument. We'll actually parse
7871 // them when we see the end of the class definition.
7872 DefArgToks.reset(new CachedTokens);
7873
7874 SourceLocation ArgStartLoc = NextToken().getLocation();
7875 ConsumeAndStoreInitializer(*DefArgToks,
7877 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
7878 ArgStartLoc);
7879 } else {
7880 // Consume the '='.
7881 ConsumeToken();
7882
7883 // The default argument may contain a lambda whose body triggers
7884 // MaybeDestroyTemplateIds at the end of the inner statements; avoid
7885 // destroying parsed template-ids that may still be referenced by
7886 // the enclosing declarator (e.g. a template-id in the function
7887 // name or other parameters).
7888 DelayTemplateIdDestructionRAII DontDestructTemplateIds(
7889 *this, /*DelayTemplateIdDestruction=*/true);
7890
7891 // The argument isn't actually potentially evaluated unless it is
7892 // used.
7893 EnterExpressionEvaluationContext Eval(
7894 Actions,
7896 Param);
7897
7898 ExprResult DefArgResult;
7899 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
7900 Diag(Tok, diag::compat_cxx11_generalized_initializer_lists);
7901 DefArgResult = ParseBraceInitializer();
7902 } else {
7903 if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
7904 Diag(Tok, diag::err_stmt_expr_in_default_arg) << 0;
7905 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
7906 /*DefaultArg=*/nullptr);
7907 // Skip the statement expression and continue parsing
7908 SkipUntil(tok::comma, StopBeforeMatch);
7909 DefArgResult = ExprError();
7910 } else {
7911 DefArgResult = ParseAssignmentExpression();
7912 }
7913 }
7914 if (DefArgResult.isInvalid()) {
7915 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
7916 /*DefaultArg=*/nullptr);
7917 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
7918 } else {
7919 // Inform the actions module about the default argument
7920 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
7921 DefArgResult.get());
7922 }
7923 }
7924 }
7925
7926 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7927 ParmDeclarator.getIdentifierLoc(),
7928 Param, std::move(DefArgToks)));
7929 }
7930
7931 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
7932 if (getLangOpts().CPlusPlus26) {
7933 // C++26 [dcl.dcl.fct]p3:
7934 // A parameter-declaration-clause of the form
7935 // parameter-list '...' is deprecated.
7936 Diag(EllipsisLoc, diag::warn_deprecated_missing_comma_before_ellipsis)
7937 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7938 }
7939
7940 if (!getLangOpts().CPlusPlus) {
7941 // We have ellipsis without a preceding ',', which is ill-formed
7942 // in C. Complain and provide the fix.
7943 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
7944 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7945 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
7946 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
7947 // It looks like this was supposed to be a parameter pack. Warn and
7948 // point out where the ellipsis should have gone.
7949 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
7950 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
7951 << ParmEllipsis.isValid() << ParmEllipsis;
7952 if (ParmEllipsis.isValid()) {
7953 Diag(ParmEllipsis,
7954 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
7955 } else {
7956 Diag(ParmDeclarator.getIdentifierLoc(),
7957 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
7958 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
7959 "...")
7960 << !ParmDeclarator.hasName();
7961 }
7962 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
7963 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7964 }
7965
7966 // We can't have any more parameters after an ellipsis.
7967 break;
7968 }
7969
7970 // If the next token is a comma, consume it and keep reading arguments.
7971 } while (TryConsumeToken(tok::comma));
7972
7973 // Every parameter is declared and still in scope, so a deferred attribute can
7974 // name any of them.
7975 if (!LateParamAttrs.empty())
7976 ParseLexedAttributeList(LateParamAttrs, /*D=*/nullptr, /*EnterScope=*/false,
7977 /*OnDefinition=*/false);
7978}
7979
7980void Parser::ParseBracketDeclarator(Declarator &D) {
7981 if (CheckProhibitedCXX11Attribute())
7982 return;
7983
7984 BalancedDelimiterTracker T(*this, tok::l_square);
7985 T.consumeOpen();
7986
7987 // C array syntax has many features, but by-far the most common is [] and [4].
7988 // This code does a fast path to handle some of the most obvious cases.
7989 if (Tok.getKind() == tok::r_square) {
7990 T.consumeClose();
7991 ParsedAttributes attrs(AttrFactory);
7992 MaybeParseCXX11Attributes(attrs);
7993
7994 // Remember that we parsed the empty array type.
7995 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
7996 T.getOpenLocation(),
7997 T.getCloseLocation()),
7998 std::move(attrs), T.getCloseLocation());
7999 return;
8000 } else if (Tok.getKind() == tok::numeric_constant &&
8001 GetLookAheadToken(1).is(tok::r_square)) {
8002 // [4] is very common. Parse the numeric constant expression.
8003 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
8004 ConsumeToken();
8005
8006 T.consumeClose();
8007 ParsedAttributes attrs(AttrFactory);
8008 MaybeParseCXX11Attributes(attrs);
8009
8010 // Remember that we parsed a array type, and remember its features.
8011 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
8012 T.getOpenLocation(),
8013 T.getCloseLocation()),
8014 std::move(attrs), T.getCloseLocation());
8015 return;
8016 } else if (Tok.getKind() == tok::code_completion) {
8017 cutOffParsing();
8018 Actions.CodeCompletion().CodeCompleteBracketDeclarator(getCurScope());
8019 return;
8020 }
8021
8022 // If valid, this location is the position where we read the 'static' keyword.
8023 SourceLocation StaticLoc;
8024 TryConsumeToken(tok::kw_static, StaticLoc);
8025
8026 // If there is a type-qualifier-list, read it now.
8027 // Type qualifiers in an array subscript are a C99 feature.
8028 DeclSpec DS(AttrFactory);
8029 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
8030
8031 // If we haven't already read 'static', check to see if there is one after the
8032 // type-qualifier-list.
8033 if (!StaticLoc.isValid())
8034 TryConsumeToken(tok::kw_static, StaticLoc);
8035
8036 // Handle "direct-declarator [ type-qual-list[opt] * ]".
8037 bool isStar = false;
8038 ExprResult NumElements;
8039
8040 // Handle the case where we have '[*]' as the array size. However, a leading
8041 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
8042 // the token after the star is a ']'. Since stars in arrays are
8043 // infrequent, use of lookahead is not costly here.
8044 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
8045 ConsumeToken(); // Eat the '*'.
8046
8047 if (StaticLoc.isValid()) {
8048 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
8049 StaticLoc = SourceLocation(); // Drop the static.
8050 }
8051 isStar = true;
8052 } else if (Tok.isNot(tok::r_square)) {
8053 // Note, in C89, this production uses the constant-expr production instead
8054 // of assignment-expr. The only difference is that assignment-expr allows
8055 // things like '=' and '*='. Sema rejects these in C89 mode because they
8056 // are not i-c-e's, so we don't need to distinguish between the two here.
8057
8058 // Parse the constant-expression or assignment-expression now (depending
8059 // on dialect).
8060 if (getLangOpts().CPlusPlus) {
8061 NumElements = ParseArrayBoundExpression();
8062 } else {
8063 EnterExpressionEvaluationContext Unevaluated(
8065 NumElements = ParseAssignmentExpression();
8066 }
8067 } else {
8068 if (StaticLoc.isValid()) {
8069 Diag(StaticLoc, diag::err_unspecified_size_with_static);
8070 StaticLoc = SourceLocation(); // Drop the static.
8071 }
8072 }
8073
8074 // If there was an error parsing the assignment-expression, recover.
8075 if (NumElements.isInvalid()) {
8076 D.setInvalidType(true);
8077 // If the expression was invalid, skip it.
8078 SkipUntil(tok::r_square, StopAtSemi);
8079 return;
8080 }
8081
8082 T.consumeClose();
8083
8084 MaybeParseCXX11Attributes(DS.getAttributes());
8085
8086 // Remember that we parsed a array type, and remember its features.
8087 D.AddTypeInfo(
8089 isStar, NumElements.get(), T.getOpenLocation(),
8090 T.getCloseLocation()),
8091 std::move(DS.getAttributes()), T.getCloseLocation());
8092}
8093
8094void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
8095 assert(Tok.is(tok::l_square) && "Missing opening bracket");
8096 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
8097
8098 SourceLocation StartBracketLoc = Tok.getLocation();
8100 D.getContext());
8101
8102 while (Tok.is(tok::l_square)) {
8103 ParseBracketDeclarator(TempDeclarator);
8104 }
8105
8106 // Stuff the location of the start of the brackets into the Declarator.
8107 // The diagnostics from ParseDirectDeclarator will make more sense if
8108 // they use this location instead.
8109 if (Tok.is(tok::semi))
8110 D.getName().EndLocation = StartBracketLoc;
8111
8112 SourceLocation SuggestParenLoc = Tok.getLocation();
8113
8114 // Now that the brackets are removed, try parsing the declarator again.
8115 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
8116
8117 // Something went wrong parsing the brackets, in which case,
8118 // ParseBracketDeclarator has emitted an error, and we don't need to emit
8119 // one here.
8120 if (TempDeclarator.getNumTypeObjects() == 0)
8121 return;
8122
8123 // Determine if parens will need to be suggested in the diagnostic.
8124 bool NeedParens = false;
8125 if (D.getNumTypeObjects() != 0) {
8126 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
8132 NeedParens = true;
8133 break;
8137 break;
8138 }
8139 }
8140
8141 if (NeedParens) {
8142 // Create a DeclaratorChunk for the inserted parens.
8143 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
8144 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
8145 SourceLocation());
8146 }
8147
8148 // Adding back the bracket info to the end of the Declarator.
8149 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
8150 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
8151 D.AddTypeInfo(Chunk, TempDeclarator.getAttributePool(), SourceLocation());
8152 }
8153
8154 // The missing name would have been diagnosed in ParseDirectDeclarator.
8155 // If parentheses are required, always suggest them.
8156 if (!D.hasName() && !NeedParens)
8157 return;
8158
8159 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
8160
8161 // Generate the move bracket error message.
8162 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
8163 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
8164
8165 if (NeedParens) {
8166 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
8167 << getLangOpts().CPlusPlus
8168 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
8169 << FixItHint::CreateInsertion(EndLoc, ")")
8171 EndLoc, CharSourceRange(BracketRange, true))
8172 << FixItHint::CreateRemoval(BracketRange);
8173 } else {
8174 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
8175 << getLangOpts().CPlusPlus
8177 EndLoc, CharSourceRange(BracketRange, true))
8178 << FixItHint::CreateRemoval(BracketRange);
8179 }
8180}
8181
8182void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
8183 assert(Tok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
8184 "Not a typeof specifier");
8185
8186 bool IsUnqual = Tok.is(tok::kw_typeof_unqual);
8187 const IdentifierInfo *II = Tok.getIdentifierInfo();
8188 if (getLangOpts().C23 && !II->getName().starts_with("__"))
8189 Diag(Tok.getLocation(), diag::warn_c23_compat_keyword) << Tok.getName();
8190
8191 Token OpTok = Tok;
8192 SourceLocation StartLoc = ConsumeToken();
8193 bool HasParens = Tok.is(tok::l_paren);
8194
8195 EnterExpressionEvaluationContext Unevaluated(
8198
8199 bool isCastExpr;
8200 ParsedType CastTy;
8201 SourceRange CastRange;
8203 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange);
8204 if (HasParens)
8205 DS.setTypeArgumentRange(CastRange);
8206
8207 if (CastRange.getEnd().isInvalid())
8208 // FIXME: Not accurate, the range gets one token more than it should.
8209 DS.SetRangeEnd(Tok.getLocation());
8210 else
8211 DS.SetRangeEnd(CastRange.getEnd());
8212
8213 if (isCastExpr) {
8214 if (!CastTy) {
8215 DS.SetTypeSpecError();
8216 return;
8217 }
8218
8219 const char *PrevSpec = nullptr;
8220 unsigned DiagID;
8221 // Check for duplicate type specifiers (e.g. "int typeof(int)").
8224 StartLoc, PrevSpec,
8225 DiagID, CastTy,
8226 Actions.getASTContext().getPrintingPolicy()))
8227 Diag(StartLoc, DiagID) << PrevSpec;
8228 return;
8229 }
8230
8231 // If we get here, the operand to the typeof was an expression.
8232 if (Operand.isInvalid()) {
8233 DS.SetTypeSpecError();
8234 return;
8235 }
8236
8237 // We might need to transform the operand if it is potentially evaluated.
8238 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
8239 if (Operand.isInvalid()) {
8240 DS.SetTypeSpecError();
8241 return;
8242 }
8243
8244 const char *PrevSpec = nullptr;
8245 unsigned DiagID;
8246 // Check for duplicate type specifiers (e.g. "int typeof(int)").
8249 StartLoc, PrevSpec,
8250 DiagID, Operand.get(),
8251 Actions.getASTContext().getPrintingPolicy()))
8252 Diag(StartLoc, DiagID) << PrevSpec;
8253}
8254
8255void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
8256 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
8257 "Not an atomic specifier");
8258
8259 SourceLocation StartLoc = ConsumeToken();
8260 BalancedDelimiterTracker T(*this, tok::l_paren);
8261 if (T.consumeOpen())
8262 return;
8263
8265 if (Result.isInvalid()) {
8266 SkipUntil(tok::r_paren, StopAtSemi);
8267 return;
8268 }
8269
8270 // Match the ')'
8271 T.consumeClose();
8272
8273 if (T.getCloseLocation().isInvalid())
8274 return;
8275
8276 DS.setTypeArgumentRange(T.getRange());
8277 DS.SetRangeEnd(T.getCloseLocation());
8278
8279 const char *PrevSpec = nullptr;
8280 unsigned DiagID;
8281 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
8282 DiagID, Result.get(),
8283 Actions.getASTContext().getPrintingPolicy()))
8284 Diag(StartLoc, DiagID) << PrevSpec;
8285}
8286
8287bool Parser::TryAltiVecVectorTokenOutOfLine() {
8288 Token Next = NextToken();
8289 switch (Next.getKind()) {
8290 default: return false;
8291 case tok::kw_short:
8292 case tok::kw_long:
8293 case tok::kw_signed:
8294 case tok::kw_unsigned:
8295 case tok::kw_void:
8296 case tok::kw_char:
8297 case tok::kw_int:
8298 case tok::kw_float:
8299 case tok::kw_double:
8300 case tok::kw_bool:
8301 case tok::kw__Bool:
8302 case tok::kw___bool:
8303 case tok::kw___pixel:
8304 Tok.setKind(tok::kw___vector);
8305 return true;
8306 case tok::identifier:
8307 if (Next.getIdentifierInfo() == Ident_pixel) {
8308 Tok.setKind(tok::kw___vector);
8309 return true;
8310 }
8311 if (Next.getIdentifierInfo() == Ident_bool ||
8312 Next.getIdentifierInfo() == Ident_Bool) {
8313 Tok.setKind(tok::kw___vector);
8314 return true;
8315 }
8316 return false;
8317 }
8318}
8319
8320bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
8321 const char *&PrevSpec, unsigned &DiagID,
8322 bool &isInvalid) {
8323 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
8324 if (Tok.getIdentifierInfo() == Ident_vector) {
8325 Token Next = NextToken();
8326 switch (Next.getKind()) {
8327 case tok::kw_short:
8328 case tok::kw_long:
8329 case tok::kw_signed:
8330 case tok::kw_unsigned:
8331 case tok::kw_void:
8332 case tok::kw_char:
8333 case tok::kw_int:
8334 case tok::kw_float:
8335 case tok::kw_double:
8336 case tok::kw_bool:
8337 case tok::kw__Bool:
8338 case tok::kw___bool:
8339 case tok::kw___pixel:
8340 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
8341 return true;
8342 case tok::identifier:
8343 if (Next.getIdentifierInfo() == Ident_pixel) {
8344 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
8345 return true;
8346 }
8347 if (Next.getIdentifierInfo() == Ident_bool ||
8348 Next.getIdentifierInfo() == Ident_Bool) {
8349 isInvalid =
8350 DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
8351 return true;
8352 }
8353 break;
8354 default:
8355 break;
8356 }
8357 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
8358 DS.isTypeAltiVecVector()) {
8359 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
8360 return true;
8361 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
8362 DS.isTypeAltiVecVector()) {
8363 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
8364 return true;
8365 }
8366 return false;
8367}
8368
8369TypeResult Parser::ParseTypeFromString(StringRef TypeStr, StringRef Context,
8370 SourceLocation IncludeLoc) {
8371 // Consume (unexpanded) tokens up to the end-of-directive.
8372 SmallVector<Token, 4> Tokens;
8373 {
8374 // Create a new buffer from which we will parse the type.
8375 auto &SourceMgr = PP.getSourceManager();
8376 FileID FID = SourceMgr.createFileID(
8377 llvm::MemoryBuffer::getMemBufferCopy(TypeStr, Context), SrcMgr::C_User,
8378 0, 0, IncludeLoc);
8379
8380 // Form a new lexer that references the buffer.
8381 Lexer L(FID, SourceMgr.getBufferOrFake(FID), PP);
8382 L.setParsingPreprocessorDirective(true);
8383
8384 // Lex the tokens from that buffer.
8385 Token Tok;
8386 do {
8387 L.Lex(Tok);
8388 Tokens.push_back(Tok);
8389 } while (Tok.isNot(tok::eod));
8390 }
8391
8392 // Replace the "eod" token with an "eof" token identifying the end of
8393 // the provided string.
8394 Token &EndToken = Tokens.back();
8395 EndToken = Token::createEof(Tok.getLocation(), TypeStr.data());
8396
8397 // Add the current token back.
8398 Tokens.push_back(Tok);
8399
8400 // Enter the tokens into the token stream.
8401 PP.EnterTokenStream(Tokens, /*DisableMacroExpansion=*/false,
8402 /*IsReinject=*/false);
8403
8404 // Consume the current token so that we'll start parsing the tokens we
8405 // added to the stream.
8407
8408 // Enter a new scope.
8409 ParseScope LocalScope(this, 0);
8410
8411 // Parse the type.
8412 TypeResult Result = ParseTypeName(nullptr);
8413
8414 // Check if we parsed the whole thing.
8415 if (Result.isUsable() &&
8416 (Tok.isNot(tok::eof) || Tok.getEofData() != TypeStr.data())) {
8417 Diag(Tok.getLocation(), diag::err_type_unparsed);
8418 }
8419
8420 // There could be leftover tokens (e.g. because of an error).
8421 // Skip through until we reach the 'end of directive' token.
8422 while (Tok.isNot(tok::eof))
8424
8425 // Consume the end token.
8426 if (Tok.is(tok::eof) && Tok.getEofData() == TypeStr.data())
8428 return Result;
8429}
8430
8431void Parser::DiagnoseBitIntUse(const Token &Tok) {
8432 // If the token is for _ExtInt, diagnose it as being deprecated. Otherwise,
8433 // the token is about _BitInt and gets (potentially) diagnosed as use of an
8434 // extension.
8435 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
8436 "expected either an _ExtInt or _BitInt token!");
8437
8438 SourceLocation Loc = Tok.getLocation();
8439 if (Tok.is(tok::kw__ExtInt)) {
8440 Diag(Loc, diag::warn_ext_int_deprecated)
8441 << FixItHint::CreateReplacement(Loc, "_BitInt");
8442 } else {
8443 // In C23 mode, diagnose that the use is not compatible with pre-C23 modes.
8444 // Otherwise, diagnose that the use is a Clang extension.
8445 if (getLangOpts().C23)
8446 Diag(Loc, diag::warn_c23_compat_keyword) << Tok.getName();
8447 else
8448 Diag(Loc, diag::ext_bit_int) << getLangOpts().CPlusPlus;
8449 }
8450}
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:77
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:184
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:189
SourceLocation getEndLoc() const
Definition DeclSpec.h:88
bool isSet() const
Deprecated.
Definition DeclSpec.h:202
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:187
void setTemplateParamLists(ArrayRef< TemplateParameterList * > L)
Definition DeclSpec.h:90
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:182
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:279
bool isVirtualSpecified() const
Definition DeclSpec.h:721
bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, ExplicitSpecifier ExplicitSpec, SourceLocation CloseParenLoc)
bool isTypeSpecPipe() const
Definition DeclSpec.h:594
void ClearTypeSpecType()
Definition DeclSpec.h:574
static const TSCS TSCS___thread
Definition DeclSpec.h:298
static const TST TST_typeof_unqualType
Definition DeclSpec.h:341
void setTypeArgumentRange(SourceRange range)
Definition DeclSpec.h:644
bool SetTypePipe(bool isPipe, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:895
SourceLocation getPipeLoc() const
Definition DeclSpec.h:674
static const TST TST_typename
Definition DeclSpec.h:338
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:627
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:764
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:314
static const TST TST_BFloat16
Definition DeclSpec.h:321
void ClearStorageClassSpecs()
Definition DeclSpec.h:566
bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
static const TSCS TSCS__Thread_local
Definition DeclSpec.h:300
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:734
TST getTypeSpecType() const
Definition DeclSpec.h:588
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:561
SCS getStorageClassSpec() const
Definition DeclSpec.h:552
bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
SourceLocation getOverflowBehaviorLoc() const
Definition DeclSpec.h:690
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:625
bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition DeclSpec.cpp:699
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:782
bool SetBitIntType(SourceLocation KWLoc, Expr *BitWidth, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:955
static const TST TST_auto_type
Definition DeclSpec.h:351
static const TST TST_interface
Definition DeclSpec.h:336
static const TST TST_double
Definition DeclSpec.h:323
static const TST TST_typeofExpr
Definition DeclSpec.h:340
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:668
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:781
bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:913
bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:735
static const TST TST_union
Definition DeclSpec.h:334
static const TST TST_char
Definition DeclSpec.h:312
static const TST TST_bool
Definition DeclSpec.h:329
static const TST TST_char16
Definition DeclSpec.h:315
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:727
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:900
static const TST TST_int
Definition DeclSpec.h:317
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:903
bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition DeclSpec.cpp:730
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:861
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:553
bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
bool hasAttributes() const
Definition DeclSpec.h:944
static const TST TST_accum
Definition DeclSpec.h:325
static const TST TST_half
Definition DeclSpec.h:320
ParsedAttributes & getAttributes()
Definition DeclSpec.h:946
bool SetOverflowBehavior(OverflowBehaviorType::OverflowBehaviorKind Kind, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:669
static const TST TST_ibm128
Definition DeclSpec.h:328
void addAttributes(const ParsedAttributesView &AL)
Concatenates two attribute lists.
Definition DeclSpec.h:940
static const TST TST_enum
Definition DeclSpec.h:333
bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:930
bool isWrapSpecified() const
Definition DeclSpec.h:681
static const TST TST_float128
Definition DeclSpec.h:327
void takeAttributesAppendingingFrom(ParsedAttributes &attrs)
Definition DeclSpec.h:954
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:710
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:670
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:342
static const TST TST_class
Definition DeclSpec.h:337
TypeSpecifierType TST
Definition DeclSpec.h:309
bool hasTagDefinition() const
Definition DeclSpec.cpp:435
static const TST TST_decimal64
Definition DeclSpec.h:331
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition DeclSpec.cpp:444
void ClearFunctionSpecs()
Definition DeclSpec.h:737
bool SetTypeQual(TQ T, SourceLocation Loc)
static const TST TST_wchar
Definition DeclSpec.h:313
static const TST TST_void
Definition DeclSpec.h:311
bool isTypeAltiVecVector() const
Definition DeclSpec.h:589
void ClearConstexprSpec()
Definition DeclSpec.h:914
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:322
static const TST TST_atomic
Definition DeclSpec.h:353
static const TST TST_fract
Definition DeclSpec.h:326
bool SetTypeSpecError()
Definition DeclSpec.cpp:947
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:562
Decl * getRepAsDecl() const
Definition DeclSpec.h:602
static const TST TST_float16
Definition DeclSpec.h:324
static const TST TST_unspecified
Definition DeclSpec.h:310
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:672
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:722
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:909
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:622
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
Definition DeclSpec.h:777
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:633
static const TSCS TSCS_thread_local
Definition DeclSpec.h:299
bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
static const TST TST_decimal32
Definition DeclSpec.h:330
bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:880
TypeSpecifierWidth getTypeSpecWidth() const
Definition DeclSpec.h:581
static const TST TST_char32
Definition DeclSpec.h:316
bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
static const TST TST_decimal128
Definition DeclSpec.h:332
bool isTypeSpecOwned() const
Definition DeclSpec.h:592
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:713
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:673
static const TST TST_int128
Definition DeclSpec.h:318
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:671
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:894
bool hasExplicitSpecifier() const
Definition DeclSpec.h:724
bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
bool hasConstexprSpecifier() const
Definition DeclSpec.h:910
static const TST TST_typeofType
Definition DeclSpec.h:339
bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition DeclSpec.cpp:740
static const TST TST_auto
Definition DeclSpec.h:350
@ PQ_StorageClassSpecifier
Definition DeclSpec.h:381
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:905
static const TST TST_struct
Definition DeclSpec.h:335
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:444
bool isInvalidDecl() const
Definition DeclBase.h:597
SourceLocation getLocation() const
Definition DeclBase.h:448
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1996
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2559
bool isPastIdentifier() const
isPastIdentifier - Return true if we have parsed beyond the point where the name would appear.
Definition DeclSpec.h:2414
void SetRangeBegin(SourceLocation Loc)
SetRangeBegin - Set the start of the source range to Loc, unless it's invalid.
Definition DeclSpec.h:2188
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2501
void setCommaLoc(SourceLocation CL)
Definition DeclSpec.h:2831
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2146
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2436
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2439
bool mayOmitIdentifier() const
mayOmitIdentifier - Return true if the identifier is either optional or not allowed.
Definition DeclSpec.h:2233
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2183
bool mayBeFollowedByCXXDirectInit() const
mayBeFollowedByCXXDirectInit - Return true if the declarator can be followed by a C++ direct initiali...
Definition DeclSpec.h:2356
bool hasGroupingParens() const
Definition DeclSpec.h:2827
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:2821
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc, const LateParsedAttrList &LateAttrs={})
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2453
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2766
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2497
bool mayHaveIdentifier() const
mayHaveIdentifier - Return true if the identifier is either optional or required.
Definition DeclSpec.h:2273
void setGroupingParens(bool flag)
Definition DeclSpec.h:2826
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2834
DeclaratorContext getContext() const
Definition DeclSpec.h:2171
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2182
void setTrailingRequiresClause(Expr *TRC)
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2729
void setHasInitializer(bool Val=true)
Definition DeclSpec.h:2853
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2165
void setTemplateParameterLists(ArrayRef< TemplateParameterList * > TPLs)
Sets the template parameter lists that preceded the declarator.
Definition DeclSpec.h:2747
bool isFirstDeclarator() const
Definition DeclSpec.h:2829
bool hasTrailingRequiresClause() const
Determine whether a trailing requires clause was written in this declarator.
Definition DeclSpec.h:2742
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2161
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition DeclSpec.h:2420
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2752
bool isFunctionDeclaratorAFunctionDeclaration() const
Return true if a function declarator at this position would be a function declaration.
Definition DeclSpec.h:2698
bool hasEllipsis() const
Definition DeclSpec.h:2833
void clear()
Reset the contents of this Declarator.
Definition DeclSpec.h:2209
void setAsmLabel(Expr *E)
Definition DeclSpec.h:2809
void ExtendWithDeclSpec(const DeclSpec &DS)
ExtendWithDeclSpec - Extend the declarator source range to include the given declspec,...
Definition DeclSpec.h:2200
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
Definition DeclSpec.h:2193
void setExtension(bool Val=true)
Definition DeclSpec.h:2812
bool isInvalidType() const
Definition DeclSpec.h:2822
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2181
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2426
bool isPrototypeContext() const
Definition DeclSpec.h:2173
void setEllipsisLoc(SourceLocation EL)
Definition DeclSpec.h:2835
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2430
Represents an enum.
Definition Decl.h:4162
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:241
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:1887
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
unsigned getMaxArgs() const
static const ParsedAttributesView & none()
Definition ParsedAttr.h:838
void prepend(iterator B, iterator E)
Definition ParsedAttr.h:880
void addAtEnd(ParsedAttr *newAttr)
Definition ParsedAttr.h:848
void remove(ParsedAttr *ToBeRemoved)
Definition ParsedAttr.h:853
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:958
void takeOneFrom(ParsedAttributes &Other, ParsedAttr *PA)
Definition ParsedAttr.h:983
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:975
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:999
ParseScope - Introduces a new scope for parsing.
Definition Parser.h:501
Parser - This implements a parser for the C family of languages.
Definition Parser.h:264
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:1882
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition Parser.cpp:100
SourceLocation getEndOfPreviousToken() const
Definition Parser.cpp:1857
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:356
Sema & getActions() const
Definition Parser.h:301
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition Parser.h:421
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:7342
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:289
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:384
friend struct LateParsedTypeAttribute
Definition Parser.h:1216
const Token & GetLookAheadToken(unsigned N)
GetLookAheadToken - This peeks ahead N tokens and returns that token without consuming any tokens.
Definition Parser.h:410
ExprResult ParseConstantExpression()
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:364
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:313
Scope * getCurScope() const
Definition Parser.h:305
ExprResult ParseArrayBoundExpression()
friend struct LateParsedAttribute
Definition Parser.h:1215
const TargetInfo & getTargetInfo() const
Definition Parser.h:299
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:600
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:304
void ExitScope()
ExitScope - Pop a scope off the scope stack.
Definition Parser.cpp:448
const LangOptions & getLangOpts() const
Definition Parser.h:298
friend class ParenBraceBracketBalancer
Definition Parser.h:292
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:581
@ StopAtCodeCompletion
Stop at code completion.
Definition Parser.h:582
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:579
ExprResult ParseUnevaluatedStringLiteralExpression()
ObjCContainerDecl * getObjCDeclContext() const
Definition Parser.h:5451
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:418
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:293
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition Parser.h:7966
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition Parser.cpp:2127
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:4476
field_range fields() const
Definition Decl.h:4679
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:141
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:3899
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9507
@ ReuseLambdaContextDecl
Definition Sema.h:7173
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6883
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6893
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6862
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6903
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:3868
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:4809
void setStmt(Stmt *S)
Definition Decl.cpp:5984
static constexpr int FunctionTypeNumParamsLimit
Definition TypeBase.h:1984
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition DeclSpec.h:1171
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1319
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1168
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1192
Declaration of a variable template.
static const char * getSpecifierName(Specifier VS)
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Attr > attr
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:1979
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:1102
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:1946
@ 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:444
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:580
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:555
@ DependentNonType
The name denotes a member of a dependent type that could not be resolved.
Definition Sema.h:569
@ UndeclaredTemplate
The name was classified as an ADL-only function template name.
Definition Sema.h:582
@ NonType
The name was classified as a specific non-type, non-template declaration.
Definition Sema.h:561
@ Unknown
This name is not a type or template in this context, but might be something else.
Definition Sema.h:551
@ Error
Classification failed; an error has been produced.
Definition Sema.h:553
@ Type
The name was classified as a type.
Definition Sema.h:557
@ TypeTemplate
The name was classified as a template whose specializations are types.
Definition Sema.h:576
@ Concept
The name was classified as a concept name.
Definition Sema.h:584
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition Sema.h:574
@ UndeclaredNonType
The name was classified as an ADL-only function name.
Definition Sema.h:565
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:578
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:218
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:1516
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1491
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:1755
static DeclaratorChunk getBlockPointer(unsigned TypeQuals, SourceLocation Loc)
Return a DeclaratorChunk for a block.
Definition DeclSpec.h:1833
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:1843
static DeclaratorChunk getArray(unsigned TypeQuals, bool isStatic, bool isStar, Expr *NumElts, SourceLocation LBLoc, SourceLocation RBLoc)
Return a DeclaratorChunk for an array.
Definition DeclSpec.h:1790
SourceLocation Loc
Loc - The place where this type was defined.
Definition DeclSpec.h:1338
FunctionTypeInfo Fun
Definition DeclSpec.h:1730
static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS, unsigned TypeQuals, SourceLocation StarLoc, SourceLocation EndLoc)
Definition DeclSpec.h:1852
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
static DeclaratorChunk getParen(SourceLocation LParenLoc, SourceLocation RParenLoc)
Return a DeclaratorChunk for a paren.
Definition DeclSpec.h:1868
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1779
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:941
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6980
bool CheckSameAsPrevious
Definition Sema.h:359
NamedDecl * New
Definition Sema.h:361
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
TemplateNameKind Kind
The kind of template that Template refers to.