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