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