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