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