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