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
388 TypeResult T;
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 ||
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 =
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 auto MayBeTypeSpecifier = [&]() {
4097 // In pre-C23 C, auto can be used as a storage-class specifier.
4098 // C23 removes auto from the storage-class specifiers and repurposes
4099 // it for type inference (6.7.10).
4100 if (getLangOpts().C23 && DS.hasTypeSpecifier() &&
4102 return true;
4103
4104 unsigned I = 1;
4105 while (true) {
4106 const Token &T = GetLookAheadToken(I);
4107 if (isKnownToBeTypeSpecifier(T))
4108 return true;
4109
4110 if (getLangOpts().C23 && isTypeSpecifierQualifier(T))
4111 ++I;
4112 else
4113 return false;
4114 }
4115 };
4116
4117 if (MayBeTypeSpecifier()) {
4119 PrevSpec, DiagID, Policy);
4120 if (!isInvalid && !getLangOpts().C23)
4121 Diag(Tok, diag::ext_auto_storage_class)
4123 } else
4124 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
4125 DiagID, Policy);
4126 } else
4128 PrevSpec, DiagID, Policy);
4129 isStorageClass = true;
4130 break;
4131 case tok::kw___auto_type:
4132 Diag(Tok, diag::ext_auto_type);
4134 DiagID, Policy);
4135 break;
4136 case tok::kw_register:
4138 PrevSpec, DiagID, Policy);
4139 isStorageClass = true;
4140 break;
4141 case tok::kw_mutable:
4143 PrevSpec, DiagID, Policy);
4144 isStorageClass = true;
4145 break;
4146 case tok::kw___thread:
4148 PrevSpec, DiagID);
4149 isStorageClass = true;
4150 break;
4151 case tok::kw_thread_local:
4152 if (getLangOpts().C23)
4153 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4154 // We map thread_local to _Thread_local in C23 mode so it retains the C
4155 // semantics rather than getting the C++ semantics.
4156 // FIXME: diagnostics will show _Thread_local when the user wrote
4157 // thread_local in source in C23 mode; we need some general way to
4158 // identify which way the user spelled the keyword in source.
4162 Loc, PrevSpec, DiagID);
4163 isStorageClass = true;
4164 break;
4165 case tok::kw__Thread_local:
4166 diagnoseUseOfC11Keyword(Tok);
4168 Loc, PrevSpec, DiagID);
4169 isStorageClass = true;
4170 break;
4171
4172 // function-specifier
4173 case tok::kw_inline:
4174 isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
4175 break;
4176 case tok::kw_virtual:
4177 // C++ for OpenCL does not allow virtual function qualifier, to avoid
4178 // function pointers restricted in OpenCL v2.0 s6.9.a.
4179 if (getLangOpts().OpenCLCPlusPlus &&
4180 !getActions().getOpenCLOptions().isAvailableOption(
4181 "__cl_clang_function_pointers", getLangOpts())) {
4182 DiagID = diag::err_openclcxx_virtual_function;
4183 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4184 isInvalid = true;
4185 } else if (getLangOpts().HLSL) {
4186 DiagID = diag::err_hlsl_virtual_function;
4187 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4188 isInvalid = true;
4189 } else {
4190 isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
4191 }
4192 break;
4193 case tok::kw_explicit: {
4194 SourceLocation ExplicitLoc = Loc;
4195 SourceLocation CloseParenLoc;
4196 ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
4197 ConsumedEnd = ExplicitLoc;
4198 ConsumeToken(); // kw_explicit
4199 if (Tok.is(tok::l_paren)) {
4200 if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
4201 Diag(Tok.getLocation(), getLangOpts().CPlusPlus20
4202 ? diag::warn_cxx17_compat_explicit_bool
4203 : diag::ext_explicit_bool);
4204
4205 ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
4206 BalancedDelimiterTracker Tracker(*this, tok::l_paren);
4207 Tracker.consumeOpen();
4208
4209 EnterExpressionEvaluationContext ConstantEvaluated(
4211
4213 ConsumedEnd = Tok.getLocation();
4214 if (ExplicitExpr.isUsable()) {
4215 CloseParenLoc = Tok.getLocation();
4216 Tracker.consumeClose();
4217 ExplicitSpec =
4218 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
4219 } else
4220 Tracker.skipToEnd();
4221 } else {
4222 Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
4223 }
4224 }
4225 isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
4226 ExplicitSpec, CloseParenLoc);
4227 break;
4228 }
4229 case tok::kw__Noreturn:
4230 diagnoseUseOfC11Keyword(Tok);
4231 isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
4232 break;
4233
4234 // friend
4235 case tok::kw_friend:
4236 if (DSContext == DeclSpecContext::DSC_class) {
4237 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
4238 Scope *CurS = getCurScope();
4239 if (!isInvalid && CurS)
4240 CurS->setFlags(CurS->getFlags() | Scope::FriendScope);
4241 } else {
4242 PrevSpec = ""; // not actually used by the diagnostic
4243 DiagID = diag::err_friend_invalid_in_context;
4244 isInvalid = true;
4245 }
4246 break;
4247
4248 // Modules
4249 case tok::kw___module_private__:
4250 isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
4251 break;
4252
4253 // constexpr, consteval, constinit specifiers
4254 case tok::kw_constexpr:
4255 if (getLangOpts().C23)
4256 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4258 PrevSpec, DiagID);
4259 break;
4260 case tok::kw_consteval:
4262 PrevSpec, DiagID);
4263 break;
4264 case tok::kw_constinit:
4266 PrevSpec, DiagID);
4267 break;
4268
4269 // type-specifier
4270 case tok::kw_short:
4271 if (!getLangOpts().NativeInt16Type) {
4272 Diag(Tok, diag::err_unknown_typename) << Tok.getName();
4273 DS.SetTypeSpecError();
4274 DS.SetRangeEnd(Tok.getLocation());
4275 ConsumeToken();
4276 goto DoneWithDeclSpec;
4277 }
4279 DiagID, Policy);
4280 break;
4281 case tok::kw_long:
4284 DiagID, Policy);
4285 else
4287 PrevSpec, DiagID, Policy);
4288 break;
4289 case tok::kw___int64:
4291 PrevSpec, DiagID, Policy);
4292 break;
4293 case tok::kw_signed:
4294 isInvalid =
4295 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4296 break;
4297 case tok::kw_unsigned:
4299 DiagID);
4300 break;
4301 case tok::kw__Complex:
4302 if (!getLangOpts().C99)
4303 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4305 DiagID);
4306 break;
4307 case tok::kw__Imaginary:
4308 if (!getLangOpts().C99)
4309 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4311 DiagID);
4312 break;
4313 case tok::kw_void:
4314 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
4315 DiagID, Policy);
4316 break;
4317 case tok::kw_char:
4318 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
4319 DiagID, Policy);
4320 break;
4321 case tok::kw_int:
4322 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
4323 DiagID, Policy);
4324 break;
4325 case tok::kw__ExtInt:
4326 case tok::kw__BitInt: {
4327 DiagnoseBitIntUse(Tok);
4328 ExprResult ER = ParseExtIntegerArgument();
4329 if (ER.isInvalid())
4330 continue;
4331 isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
4332 ConsumedEnd = PrevTokLocation;
4333 break;
4334 }
4335 case tok::kw___int128:
4337 DiagID, Policy);
4338 break;
4339 case tok::kw_half:
4340 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
4341 DiagID, Policy);
4342 break;
4343 case tok::kw___bf16:
4345 DiagID, Policy);
4346 break;
4347 case tok::kw_float:
4348 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
4349 DiagID, Policy);
4350 break;
4351 case tok::kw_double:
4353 DiagID, Policy);
4354 break;
4355 case tok::kw__Float16:
4357 DiagID, Policy);
4358 break;
4359 case tok::kw__Accum:
4360 assert(getLangOpts().FixedPoint &&
4361 "This keyword is only used when fixed point types are enabled "
4362 "with `-ffixed-point`");
4363 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec, DiagID,
4364 Policy);
4365 break;
4366 case tok::kw__Fract:
4367 assert(getLangOpts().FixedPoint &&
4368 "This keyword is only used when fixed point types are enabled "
4369 "with `-ffixed-point`");
4370 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec, DiagID,
4371 Policy);
4372 break;
4373 case tok::kw__Sat:
4374 assert(getLangOpts().FixedPoint &&
4375 "This keyword is only used when fixed point types are enabled "
4376 "with `-ffixed-point`");
4377 isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
4378 break;
4379 case tok::kw___float128:
4381 DiagID, Policy);
4382 break;
4383 case tok::kw___ibm128:
4385 DiagID, Policy);
4386 break;
4387 case tok::kw_wchar_t:
4388 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
4389 DiagID, Policy);
4390 break;
4391 case tok::kw_char8_t:
4392 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
4393 DiagID, Policy);
4394 break;
4395 case tok::kw_char16_t:
4397 DiagID, Policy);
4398 break;
4399 case tok::kw_char32_t:
4401 DiagID, Policy);
4402 break;
4403 case tok::kw_bool:
4404 if (getLangOpts().C23)
4405 Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
4406 [[fallthrough]];
4407 case tok::kw__Bool:
4408 if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
4409 Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4410
4411 if (Tok.is(tok::kw_bool) &&
4414 PrevSpec = ""; // Not used by the diagnostic.
4415 DiagID = diag::err_bool_redeclaration;
4416 // For better error recovery.
4417 Tok.setKind(tok::identifier);
4418 isInvalid = true;
4419 } else {
4420 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
4421 DiagID, Policy);
4422 }
4423 break;
4424 case tok::kw__Decimal32:
4426 DiagID, Policy);
4427 break;
4428 case tok::kw__Decimal64:
4430 DiagID, Policy);
4431 break;
4432 case tok::kw__Decimal128:
4434 DiagID, Policy);
4435 break;
4436 case tok::kw___vector:
4437 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4438 break;
4439 case tok::kw___pixel:
4440 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4441 break;
4442 case tok::kw___bool:
4443 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4444 break;
4445 case tok::kw_pipe:
4446 if (!getLangOpts().OpenCL ||
4447 getLangOpts().getOpenCLCompatibleVersion() < 200) {
4448 // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4449 // should support the "pipe" word as identifier.
4450 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
4451 Tok.setKind(tok::identifier);
4452 goto DoneWithDeclSpec;
4453 } else if (!getLangOpts().OpenCLPipes) {
4454 DiagID = diag::err_opencl_unknown_type_specifier;
4455 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4456 isInvalid = true;
4457 } else
4458 isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4459 break;
4460// We only need to enumerate each image type once.
4461#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4462#define IMAGE_WRITE_TYPE(Type, Id, Ext)
4463#define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4464 case tok::kw_##ImgType##_t: \
4465 if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4466 goto DoneWithDeclSpec; \
4467 break;
4468#include "clang/Basic/OpenCLImageTypes.def"
4469 case tok::kw___unknown_anytype:
4471 PrevSpec, DiagID, Policy);
4472 break;
4473
4474 // class-specifier:
4475 case tok::kw_class:
4476 case tok::kw_struct:
4477 case tok::kw___interface:
4478 case tok::kw_union: {
4479 tok::TokenKind Kind = Tok.getKind();
4480 ConsumeToken();
4481
4482 // These are attributes following class specifiers.
4483 // To produce better diagnostic, we parse them when
4484 // parsing class specifier.
4485 ParsedAttributes Attributes(AttrFactory);
4486 ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4487 EnteringContext, DSContext, Attributes);
4488
4489 // If there are attributes following class specifier,
4490 // take them over and handle them here.
4491 if (!Attributes.empty()) {
4492 AttrsLastTime = true;
4493 attrs.takeAllAppendingFrom(Attributes);
4494 }
4495 continue;
4496 }
4497
4498 // enum-specifier:
4499 case tok::kw_enum:
4500 ConsumeToken();
4501 ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4502 continue;
4503
4504 // cv-qualifier:
4505 case tok::kw_const:
4506 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4507 getLangOpts());
4508 break;
4509 case tok::kw_volatile:
4510 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4511 getLangOpts());
4512 break;
4513 case tok::kw_restrict:
4514 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4515 getLangOpts());
4516 break;
4517 case tok::kw___ob_wrap:
4518 if (!getLangOpts().OverflowBehaviorTypes) {
4519 Diag(Loc, diag::warn_overflow_behavior_keyword_disabled)
4520 << tok::getKeywordSpelling(Tok.getKind());
4521 break;
4522 }
4524 OverflowBehaviorType::OverflowBehaviorKind::Wrap, Loc, PrevSpec,
4525 DiagID);
4526 break;
4527 case tok::kw___ob_trap:
4528 if (!getLangOpts().OverflowBehaviorTypes) {
4529 Diag(Loc, diag::warn_overflow_behavior_keyword_disabled)
4530 << tok::getKeywordSpelling(Tok.getKind());
4531 break;
4532 }
4534 OverflowBehaviorType::OverflowBehaviorKind::Trap, Loc, PrevSpec,
4535 DiagID);
4536 break;
4537
4538 // C++ typename-specifier:
4539 case tok::kw_typename:
4541 DS.SetTypeSpecError();
4542 goto DoneWithDeclSpec;
4543 }
4544 if (!Tok.is(tok::kw_typename))
4545 continue;
4546 break;
4547
4548 // C23/GNU typeof support.
4549 case tok::kw_typeof:
4550 case tok::kw_typeof_unqual:
4551 ParseTypeofSpecifier(DS);
4552 continue;
4553
4554 case tok::annot_decltype:
4555 ParseDecltypeSpecifier(DS);
4556 continue;
4557
4558 case tok::annot_pack_indexing_type:
4559 ParsePackIndexingType(DS);
4560 continue;
4561
4562 case tok::annot_pragma_pack:
4563 HandlePragmaPack();
4564 continue;
4565
4566 case tok::annot_pragma_ms_pragma:
4567 HandlePragmaMSPragma();
4568 continue;
4569
4570 case tok::annot_pragma_ms_vtordisp:
4571 HandlePragmaMSVtorDisp();
4572 continue;
4573
4574 case tok::annot_pragma_ms_pointers_to_members:
4575 HandlePragmaMSPointersToMembers();
4576 continue;
4577
4578 case tok::annot_pragma_export:
4579 HandlePragmaExport();
4580 continue;
4581
4582#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
4583#include "clang/Basic/TransformTypeTraits.def"
4584 // HACK: libstdc++ already uses '__remove_cv' as an alias template so we
4585 // work around this by expecting all transform type traits to be suffixed
4586 // with '('. They're an identifier otherwise.
4587 if (!MaybeParseTypeTransformTypeSpecifier(DS))
4588 goto ParseIdentifier;
4589 continue;
4590
4591 case tok::kw__Atomic:
4592 // C11 6.7.2.4/4:
4593 // If the _Atomic keyword is immediately followed by a left parenthesis,
4594 // it is interpreted as a type specifier (with a type name), not as a
4595 // type qualifier.
4596 diagnoseUseOfC11Keyword(Tok);
4597 if (NextToken().is(tok::l_paren)) {
4598 ParseAtomicSpecifier(DS);
4599 continue;
4600 }
4601 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4602 getLangOpts());
4603 break;
4604
4605 // OpenCL address space qualifiers:
4606 case tok::kw___generic:
4607 // generic address space is introduced only in OpenCL v2.0
4608 // see OpenCL C Spec v2.0 s6.5.5
4609 // OpenCL v3.0 introduces __opencl_c_generic_address_space
4610 // feature macro to indicate if generic address space is supported
4611 if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4612 DiagID = diag::err_opencl_unknown_type_specifier;
4613 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4614 isInvalid = true;
4615 break;
4616 }
4617 [[fallthrough]];
4618 case tok::kw_private:
4619 // It's fine (but redundant) to check this for __generic on the
4620 // fallthrough path; we only form the __generic token in OpenCL mode.
4621 if (!getLangOpts().OpenCL)
4622 goto DoneWithDeclSpec;
4623 [[fallthrough]];
4624 case tok::kw___private:
4625 case tok::kw___global:
4626 case tok::kw___local:
4627 case tok::kw___constant:
4628 // OpenCL access qualifiers:
4629 case tok::kw___read_only:
4630 case tok::kw___write_only:
4631 case tok::kw___read_write:
4632 ParseOpenCLQualifiers(DS.getAttributes());
4633 break;
4634
4635 case tok::kw_groupshared:
4636 case tok::kw_in:
4637 case tok::kw_inout:
4638 case tok::kw_out:
4639 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4640 ParseHLSLQualifiers(DS.getAttributes());
4641 continue;
4642
4643#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
4644 case tok::kw_##Name: \
4645 isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##Name, Loc, PrevSpec, \
4646 DiagID, Policy); \
4647 break;
4648#include "clang/Basic/HLSLIntangibleTypes.def"
4649
4650 case tok::less:
4651 // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4652 // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4653 // but we support it.
4654 if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4655 goto DoneWithDeclSpec;
4656
4657 SourceLocation StartLoc = Tok.getLocation();
4658 SourceLocation EndLoc;
4659 TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4660 if (Type.isUsable()) {
4661 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4662 PrevSpec, DiagID, Type.get(),
4663 Actions.getASTContext().getPrintingPolicy()))
4664 Diag(StartLoc, DiagID) << PrevSpec;
4665
4666 DS.SetRangeEnd(EndLoc);
4667 } else {
4668 DS.SetTypeSpecError();
4669 }
4670
4671 // Need to support trailing type qualifiers (e.g. "id<p> const").
4672 // If a type specifier follows, it will be diagnosed elsewhere.
4673 continue;
4674 }
4675
4676 DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4677
4678 // If the specifier wasn't legal, issue a diagnostic.
4679 if (isInvalid) {
4680 assert(PrevSpec && "Method did not return previous specifier!");
4681 assert(DiagID);
4682
4683 if (DiagID == diag::ext_duplicate_declspec ||
4684 DiagID == diag::ext_warn_duplicate_declspec ||
4685 DiagID == diag::err_duplicate_declspec)
4686 Diag(Loc, DiagID) << PrevSpec
4688 SourceRange(Loc, DS.getEndLoc()));
4689 else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4690 Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4691 << isStorageClass;
4692 } else
4693 Diag(Loc, DiagID) << PrevSpec;
4694 }
4695
4696 if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4697 // After an error the next token can be an annotation token.
4699
4700 AttrsLastTime = false;
4701 }
4702}
4703
4705 Parser &P) {
4706
4708 return;
4709
4710 auto *RD = dyn_cast<RecordDecl>(DS.getRepAsDecl());
4711 // We're only interested in unnamed, non-anonymous struct
4712 if (!RD || !RD->getName().empty() || RD->isAnonymousStructOrUnion())
4713 return;
4714
4715 for (auto *I : RD->decls()) {
4716 auto *VD = dyn_cast<ValueDecl>(I);
4717 if (!VD)
4718 continue;
4719
4720 auto *CAT = VD->getType()->getAs<CountAttributedType>();
4721 if (!CAT)
4722 continue;
4723
4724 for (const auto &DD : CAT->dependent_decls()) {
4725 if (!RD->containsDecl(DD.getDecl())) {
4726 P.Diag(VD->getBeginLoc(), diag::err_count_attr_param_not_in_same_struct)
4727 << DD.getDecl() << CAT->getKind() << CAT->isArrayType();
4728 P.Diag(DD.getDecl()->getBeginLoc(),
4729 diag::note_flexible_array_counted_by_attr_field)
4730 << DD.getDecl();
4731 }
4732 }
4733 }
4734}
4735
4736void Parser::ParseStructDeclaration(
4737 ParsingDeclSpec &DS,
4738 llvm::function_ref<Decl *(ParsingFieldDeclarator &)> FieldsCallback,
4739 LateParsedAttrList *LateFieldAttrs) {
4740
4741 if (Tok.is(tok::kw___extension__)) {
4742 // __extension__ silences extension warnings in the subexpression.
4743 ExtensionRAIIObject O(Diags); // Use RAII to do this.
4744 ConsumeToken();
4745 return ParseStructDeclaration(DS, FieldsCallback, LateFieldAttrs);
4746 }
4747
4748 // Parse leading attributes.
4749 ParsedAttributes Attrs(AttrFactory);
4750 MaybeParseCXX11Attributes(Attrs);
4751
4752 // Parse the common specifier-qualifiers-list piece.
4753 ParseSpecifierQualifierList(DS);
4754
4755 // If there are no declarators, this is a free-standing declaration
4756 // specifier. Let the actions module cope with it.
4757 if (Tok.is(tok::semi)) {
4758 // C23 6.7.2.1p9 : "The optional attribute specifier sequence in a
4759 // member declaration appertains to each of the members declared by the
4760 // member declarator list; it shall not appear if the optional member
4761 // declarator list is omitted."
4762 ProhibitAttributes(Attrs);
4763 RecordDecl *AnonRecord = nullptr;
4764 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
4765 getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
4766 assert(!AnonRecord && "Did not expect anonymous struct or union here");
4767 DS.complete(TheDecl);
4768 return;
4769 }
4770
4771 // Read struct-declarators until we find the semicolon.
4772 bool FirstDeclarator = true;
4773 SourceLocation CommaLoc;
4774 while (true) {
4775 ParsingFieldDeclarator DeclaratorInfo(*this, DS, Attrs);
4776 DeclaratorInfo.D.setCommaLoc(CommaLoc);
4777
4778 // Attributes are only allowed here on successive declarators.
4779 if (!FirstDeclarator) {
4780 // However, this does not apply for [[]] attributes (which could show up
4781 // before or after the __attribute__ attributes).
4782 DiagnoseAndSkipCXX11Attributes();
4783 MaybeParseGNUAttributes(DeclaratorInfo.D);
4784 DiagnoseAndSkipCXX11Attributes();
4785 }
4786
4787 /// struct-declarator: declarator
4788 /// struct-declarator: declarator[opt] ':' constant-expression
4789 if (Tok.isNot(tok::colon)) {
4790 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4792 ParseDeclarator(DeclaratorInfo.D);
4793 } else
4794 DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4795
4796 // Here, we now know that the unnamed struct is not an anonymous struct.
4797 // Report an error if a counted_by attribute refers to a field in a
4798 // different named struct.
4800
4801 if (TryConsumeToken(tok::colon)) {
4803 if (Res.isInvalid())
4804 SkipUntil(tok::semi, StopBeforeMatch);
4805 else
4806 DeclaratorInfo.BitfieldSize = Res.get();
4807 }
4808
4809 // If attributes exist after the declarator, parse them.
4810 MaybeParseGNUAttributes(DeclaratorInfo.D, LateFieldAttrs);
4811
4812 // We're done with this declarator; invoke the callback.
4813 Decl *Field = FieldsCallback(DeclaratorInfo);
4814 if (Field)
4815 DistributeCLateParsedAttrs(Field, LateFieldAttrs);
4816
4817 // If we don't have a comma, it is either the end of the list (a ';')
4818 // or an error, bail out.
4819 if (!TryConsumeToken(tok::comma, CommaLoc))
4820 return;
4821
4822 FirstDeclarator = false;
4823 }
4824}
4825
4826// TODO: All callers of this function should be moved to
4827// `Parser::ParseLexedAttributeList`.
4828void Parser::ParseLexedCAttributeList(LateParsedAttrList &LAs, bool EnterScope,
4829 ParsedAttributes *OutAttrs) {
4830 assert(LAs.parseSoon() &&
4831 "Attribute list should be marked for immediate parsing.");
4832 for (auto *LA : LAs) {
4833 ParseLexedCAttribute(*LA, EnterScope, OutAttrs);
4834 delete LA;
4835 }
4836 LAs.clear();
4837}
4838
4839void Parser::ParseLexedCAttribute(LateParsedAttribute &LA, bool EnterScope,
4840 ParsedAttributes *OutAttrs) {
4841 // Create a fake EOF so that attribute parsing won't go off the end of the
4842 // attribute.
4843 Token AttrEnd;
4844 AttrEnd.startToken();
4845 AttrEnd.setKind(tok::eof);
4846 AttrEnd.setLocation(Tok.getLocation());
4847 AttrEnd.setEofData(LA.Toks.data());
4848 LA.Toks.push_back(AttrEnd);
4849
4850 // Append the current token at the end of the new token stream so that it
4851 // doesn't get lost.
4852 LA.Toks.push_back(Tok);
4853 PP.EnterTokenStream(LA.Toks, /*DisableMacroExpansion=*/true,
4854 /*IsReinject=*/true);
4855 // Drop the current token and bring the first cached one. It's the same token
4856 // as when we entered this function.
4857 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
4858
4859 // TODO: Use `EnterScope`
4860 (void)EnterScope;
4861
4862 ParsedAttributes Attrs(AttrFactory);
4863
4864 assert(LA.Decls.size() <= 1 &&
4865 "late field attribute expects to have at most one declaration.");
4866
4867 // Dispatch based on the attribute and parse it
4868 ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, nullptr, nullptr,
4869 SourceLocation(), ParsedAttr::Form::GNU(), nullptr);
4870
4871 for (auto *D : LA.Decls)
4872 Actions.ActOnFinishDelayedAttribute(getCurScope(), D, Attrs);
4873
4874 // Due to a parsing error, we either went over the cached tokens or
4875 // there are still cached tokens left, so we skip the leftover tokens.
4876 while (Tok.isNot(tok::eof))
4878
4879 // Consume the fake EOF token if it's there
4880 if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
4882
4883 if (OutAttrs) {
4884 OutAttrs->takeAllAppendingFrom(Attrs);
4885 }
4886}
4887
4888void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4889 DeclSpec::TST TagType, RecordDecl *TagDecl) {
4890 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4891 "parsing struct/union body");
4892 assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4893
4894 BalancedDelimiterTracker T(*this, tok::l_brace);
4895 if (T.consumeOpen())
4896 return;
4897
4899 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4900
4901 // `LateAttrParseExperimentalExtOnly=true` requests that only attributes
4902 // marked with `LateAttrParseExperimentalExt` are late parsed.
4903 LateParsedAttrList LateFieldAttrs(/*PSoon=*/true,
4904 /*LateAttrParseExperimentalExtOnly=*/true);
4905
4906 // While we still have something to read, read the declarations in the struct.
4907 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4908 Tok.isNot(tok::eof)) {
4909 // Each iteration of this loop reads one struct-declaration.
4910
4911 // Check for extraneous top-level semicolon.
4912 if (Tok.is(tok::semi)) {
4913 ConsumeExtraSemi(ExtraSemiKind::InsideStruct, TagType);
4914 continue;
4915 }
4916
4917 // Parse _Static_assert declaration.
4918 if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
4919 SourceLocation DeclEnd;
4920 ParseStaticAssertDeclaration(DeclEnd);
4921 continue;
4922 }
4923
4924 if (Tok.is(tok::annot_pragma_pack)) {
4925 HandlePragmaPack();
4926 continue;
4927 }
4928
4929 if (Tok.is(tok::annot_pragma_align)) {
4930 HandlePragmaAlign();
4931 continue;
4932 }
4933
4934 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
4935 // Result can be ignored, because it must be always empty.
4937 ParsedAttributes Attrs(AttrFactory);
4938 (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4939 continue;
4940 }
4941
4942 if (Tok.is(tok::annot_pragma_openacc)) {
4944 ParsedAttributes Attrs(AttrFactory);
4945 ParseOpenACCDirectiveDecl(AS, Attrs, TagType, TagDecl);
4946 continue;
4947 }
4948
4949 if (tok::isPragmaAnnotation(Tok.getKind())) {
4950 Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4952 TagType, Actions.getASTContext().getPrintingPolicy());
4953 ConsumeAnnotationToken();
4954 continue;
4955 }
4956
4957 if (!Tok.is(tok::at)) {
4958 auto CFieldCallback = [&](ParsingFieldDeclarator &FD) -> Decl * {
4959 // Install the declarator into the current TagDecl.
4960 Decl *Field =
4961 Actions.ActOnField(getCurScope(), TagDecl,
4962 FD.D.getDeclSpec().getSourceRange().getBegin(),
4963 FD.D, FD.BitfieldSize);
4964 FD.complete(Field);
4965 return Field;
4966 };
4967
4968 // Parse all the comma separated declarators.
4969 ParsingDeclSpec DS(*this);
4970 ParseStructDeclaration(DS, CFieldCallback, &LateFieldAttrs);
4971 } else { // Handle @defs
4972 ConsumeToken();
4973 if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4974 Diag(Tok, diag::err_unexpected_at);
4975 SkipUntil(tok::semi);
4976 continue;
4977 }
4978 ConsumeToken();
4979 ExpectAndConsume(tok::l_paren);
4980 if (!Tok.is(tok::identifier)) {
4981 Diag(Tok, diag::err_expected) << tok::identifier;
4982 SkipUntil(tok::semi);
4983 continue;
4984 }
4985 SmallVector<Decl *, 16> Fields;
4986 Actions.ObjC().ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4987 Tok.getIdentifierInfo(), Fields);
4988 ConsumeToken();
4989 ExpectAndConsume(tok::r_paren);
4990 }
4991
4992 if (TryConsumeToken(tok::semi))
4993 continue;
4994
4995 if (Tok.is(tok::r_brace)) {
4996 ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4997 break;
4998 }
4999
5000 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
5001 // Skip to end of block or statement to avoid ext-warning on extra ';'.
5002 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
5003 // If we stopped at a ';', eat it.
5004 TryConsumeToken(tok::semi);
5005 }
5006
5007 T.consumeClose();
5008
5009 ParsedAttributes attrs(AttrFactory);
5010 // If attributes exist after struct contents, parse them.
5011 MaybeParseGNUAttributes(attrs, &LateFieldAttrs);
5012
5013 // Late parse field attributes if necessary.
5014 ParseLexedCAttributeList(LateFieldAttrs, /*EnterScope=*/false);
5015
5016 SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
5017
5018 Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
5019 T.getOpenLocation(), T.getCloseLocation(), attrs);
5020 StructScope.Exit();
5021 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
5022}
5023
5024void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
5025 const ParsedTemplateInfo &TemplateInfo,
5026 AccessSpecifier AS, DeclSpecContext DSC) {
5027 // Parse the tag portion of this.
5028 if (Tok.is(tok::code_completion)) {
5029 // Code completion for an enum name.
5030 cutOffParsing();
5031 Actions.CodeCompletion().CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
5032 DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
5033 return;
5034 }
5035
5036 // If attributes exist after tag, parse them.
5037 ParsedAttributes attrs(AttrFactory);
5038 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
5039
5040 SourceLocation ScopedEnumKWLoc;
5041 bool IsScopedUsingClassTag = false;
5042
5043 // In C++11, recognize 'enum class' and 'enum struct'.
5044 if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
5045 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
5046 : diag::ext_scoped_enum);
5047 IsScopedUsingClassTag = Tok.is(tok::kw_class);
5048 ScopedEnumKWLoc = ConsumeToken();
5049
5050 // Attributes are not allowed between these keywords. Diagnose,
5051 // but then just treat them like they appeared in the right place.
5052 ProhibitAttributes(attrs);
5053
5054 // They are allowed afterwards, though.
5055 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
5056 }
5057
5058 // C++11 [temp.explicit]p12:
5059 // The usual access controls do not apply to names used to specify
5060 // explicit instantiations.
5061 // We extend this to also cover explicit specializations. Note that
5062 // we don't suppress if this turns out to be an elaborated type
5063 // specifier.
5064 bool shouldDelayDiagsInTag =
5065 (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation ||
5066 TemplateInfo.Kind == ParsedTemplateKind::ExplicitSpecialization);
5067 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
5068
5069 // Determine whether this declaration is permitted to have an enum-base.
5070 AllowDefiningTypeSpec AllowEnumSpecifier =
5071 isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus);
5072 bool CanBeOpaqueEnumDeclaration =
5073 DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
5074 bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
5075 getLangOpts().MicrosoftExt) &&
5076 (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
5077 CanBeOpaqueEnumDeclaration);
5078
5079 CXXScopeSpec &SS = DS.getTypeSpecScope();
5080 if (getLangOpts().CPlusPlus) {
5081 // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
5083
5084 CXXScopeSpec Spec;
5085 if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
5086 /*ObjectHasErrors=*/false,
5087 /*EnteringContext=*/true))
5088 return;
5089
5090 if (Spec.isSet() && Tok.isNot(tok::identifier)) {
5091 Diag(Tok, diag::err_expected) << tok::identifier;
5092 DS.SetTypeSpecError();
5093 if (Tok.isNot(tok::l_brace)) {
5094 // Has no name and is not a definition.
5095 // Skip the rest of this declarator, up until the comma or semicolon.
5096 SkipUntil(tok::comma, StopAtSemi);
5097 return;
5098 }
5099 }
5100
5101 SS = std::move(Spec);
5102 }
5103
5104 // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
5105 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
5106 Tok.isNot(tok::colon)) {
5107 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
5108
5109 DS.SetTypeSpecError();
5110 // Skip the rest of this declarator, up until the comma or semicolon.
5111 SkipUntil(tok::comma, StopAtSemi);
5112 return;
5113 }
5114
5115 // If an identifier is present, consume and remember it.
5116 IdentifierInfo *Name = nullptr;
5117 SourceLocation NameLoc;
5118 if (Tok.is(tok::identifier)) {
5119 Name = Tok.getIdentifierInfo();
5120 NameLoc = ConsumeToken();
5121 }
5122
5123 if (!Name && ScopedEnumKWLoc.isValid()) {
5124 // C++0x 7.2p2: The optional identifier shall not be omitted in the
5125 // declaration of a scoped enumeration.
5126 Diag(Tok, diag::err_scoped_enum_missing_identifier);
5127 ScopedEnumKWLoc = SourceLocation();
5128 IsScopedUsingClassTag = false;
5129 }
5130
5131 // Okay, end the suppression area. We'll decide whether to emit the
5132 // diagnostics in a second.
5133 if (shouldDelayDiagsInTag)
5134 diagsFromTag.done();
5135
5136 TypeResult BaseType;
5137 SourceRange BaseRange;
5138
5139 bool CanBeBitfield =
5140 getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
5141
5142 // Parse the fixed underlying type.
5143 if (Tok.is(tok::colon)) {
5144 // This might be an enum-base or part of some unrelated enclosing context.
5145 //
5146 // 'enum E : base' is permitted in two circumstances:
5147 //
5148 // 1) As a defining-type-specifier, when followed by '{'.
5149 // 2) As the sole constituent of a complete declaration -- when DS is empty
5150 // and the next token is ';'.
5151 //
5152 // The restriction to defining-type-specifiers is important to allow parsing
5153 // a ? new enum E : int{}
5154 // _Generic(a, enum E : int{})
5155 // properly.
5156 //
5157 // One additional consideration applies:
5158 //
5159 // C++ [dcl.enum]p1:
5160 // A ':' following "enum nested-name-specifier[opt] identifier" within
5161 // the decl-specifier-seq of a member-declaration is parsed as part of
5162 // an enum-base.
5163 //
5164 // Other language modes supporting enumerations with fixed underlying types
5165 // do not have clear rules on this, so we disambiguate to determine whether
5166 // the tokens form a bit-field width or an enum-base.
5167
5168 if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
5169 // Outside C++11, do not interpret the tokens as an enum-base if they do
5170 // not make sense as one. In C++11, it's an error if this happens.
5172 Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
5173 } else if (CanHaveEnumBase || !ColonIsSacred) {
5174 SourceLocation ColonLoc = ConsumeToken();
5175
5176 // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
5177 // because under -fms-extensions,
5178 // enum E : int *p;
5179 // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
5180 DeclSpec DS(AttrFactory);
5181 // enum-base is not assumed to be a type and therefore requires the
5182 // typename keyword [p0634r3].
5183 ParseSpecifierQualifierList(DS, ImplicitTypenameContext::No, AS,
5184 DeclSpecContext::DSC_type_specifier);
5185 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
5187 BaseType = Actions.ActOnTypeName(DeclaratorInfo);
5188
5189 BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
5190
5191 if (!getLangOpts().ObjC) {
5192 if (getLangOpts().CPlusPlus)
5193 DiagCompat(ColonLoc, diag_compat::enum_fixed_underlying_type)
5194 << BaseRange;
5195 else if (getLangOpts().MicrosoftExt && !getLangOpts().C23)
5196 Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
5197 << BaseRange;
5198 else
5199 Diag(ColonLoc, getLangOpts().C23
5200 ? diag::warn_c17_compat_enum_fixed_underlying_type
5201 : diag::ext_c23_enum_fixed_underlying_type)
5202 << BaseRange;
5203 }
5204 }
5205 }
5206
5207 // There are four options here. If we have 'friend enum foo;' then this is a
5208 // friend declaration, and cannot have an accompanying definition. If we have
5209 // 'enum foo;', then this is a forward declaration. If we have
5210 // 'enum foo {...' then this is a definition. Otherwise we have something
5211 // like 'enum foo xyz', a reference.
5212 //
5213 // This is needed to handle stuff like this right (C99 6.7.2.3p11):
5214 // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
5215 // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
5216 //
5217 TagUseKind TUK;
5218 if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
5220 else if (Tok.is(tok::l_brace)) {
5221 if (DS.isFriendSpecified()) {
5222 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
5223 << SourceRange(DS.getFriendSpecLoc());
5224 ConsumeBrace();
5225 SkipUntil(tok::r_brace, StopAtSemi);
5226 // Discard any other definition-only pieces.
5227 attrs.clear();
5228 ScopedEnumKWLoc = SourceLocation();
5229 IsScopedUsingClassTag = false;
5230 BaseType = TypeResult();
5231 TUK = TagUseKind::Friend;
5232 } else {
5234 }
5235 } else if (!isTypeSpecifier(DSC) &&
5236 (Tok.is(tok::semi) ||
5237 (Tok.isAtStartOfLine() &&
5238 !isValidAfterTypeSpecifier(CanBeBitfield)))) {
5239 // An opaque-enum-declaration is required to be standalone (no preceding or
5240 // following tokens in the declaration). Sema enforces this separately by
5241 // diagnosing anything else in the DeclSpec.
5243 if (Tok.isNot(tok::semi)) {
5244 // A semicolon was missing after this declaration. Diagnose and recover.
5245 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5246 PP.EnterToken(Tok, /*IsReinject=*/true);
5247 Tok.setKind(tok::semi);
5248 }
5249 } else {
5251 }
5252
5253 bool IsElaboratedTypeSpecifier =
5255
5256 // If this is an elaborated type specifier nested in a larger declaration,
5257 // and we delayed diagnostics before, just merge them into the current pool.
5258 if (TUK == TagUseKind::Reference && shouldDelayDiagsInTag) {
5259 diagsFromTag.redelay();
5260 }
5261
5262 MultiTemplateParamsArg TParams;
5263 if (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate &&
5264 TUK != TagUseKind::Reference) {
5265 if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
5266 // Skip the rest of this declarator, up until the comma or semicolon.
5267 Diag(Tok, diag::err_enum_template);
5268 SkipUntil(tok::comma, StopAtSemi);
5269 return;
5270 }
5271
5272 if (TemplateInfo.Kind == ParsedTemplateKind::ExplicitInstantiation) {
5273 // Enumerations can't be explicitly instantiated.
5274 DS.SetTypeSpecError();
5275 Diag(StartLoc, diag::err_explicit_instantiation_enum);
5276 return;
5277 }
5278
5279 assert(TemplateInfo.TemplateParams && "no template parameters");
5280 TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
5281 TemplateInfo.TemplateParams->size());
5282 SS.setTemplateParamLists(TParams);
5283 }
5284
5285 if (!Name && TUK != TagUseKind::Definition) {
5286 Diag(Tok, diag::err_enumerator_unnamed_no_def);
5287
5288 DS.SetTypeSpecError();
5289 // Skip the rest of this declarator, up until the comma or semicolon.
5290 SkipUntil(tok::comma, StopAtSemi);
5291 return;
5292 }
5293
5294 // An elaborated-type-specifier has a much more constrained grammar:
5295 //
5296 // 'enum' nested-name-specifier[opt] identifier
5297 //
5298 // If we parsed any other bits, reject them now.
5299 //
5300 // MSVC and (for now at least) Objective-C permit a full enum-specifier
5301 // or opaque-enum-declaration anywhere.
5302 if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
5303 !getLangOpts().ObjC) {
5304 ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
5305 diag::err_keyword_not_allowed,
5306 /*DiagnoseEmptyAttrs=*/true);
5307 if (BaseType.isUsable())
5308 Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
5309 << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
5310 else if (ScopedEnumKWLoc.isValid())
5311 Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
5312 << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
5313 }
5314
5315 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
5316
5317 SkipBodyInfo SkipBody;
5318 if (!Name && TUK == TagUseKind::Definition && Tok.is(tok::l_brace) &&
5319 NextToken().is(tok::identifier))
5320 SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
5321 NextToken().getIdentifierInfo(),
5322 NextToken().getLocation());
5323
5324 bool Owned = false;
5325 bool IsDependent = false;
5326 const char *PrevSpec = nullptr;
5327 unsigned DiagID;
5328 Decl *TagDecl =
5329 Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS,
5330 Name, NameLoc, attrs, AS, DS.getModulePrivateSpecLoc(),
5331 TParams, Owned, IsDependent, ScopedEnumKWLoc,
5332 IsScopedUsingClassTag,
5333 BaseType, DSC == DeclSpecContext::DSC_type_specifier,
5334 DSC == DeclSpecContext::DSC_template_param ||
5335 DSC == DeclSpecContext::DSC_template_type_arg,
5336 OffsetOfState, &SkipBody).get();
5337
5338 if (SkipBody.ShouldSkip) {
5339 assert(TUK == TagUseKind::Definition && "can only skip a definition");
5340
5341 BalancedDelimiterTracker T(*this, tok::l_brace);
5342 T.consumeOpen();
5343 T.skipToEnd();
5344
5345 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5346 NameLoc.isValid() ? NameLoc : StartLoc,
5347 PrevSpec, DiagID, TagDecl, Owned,
5348 Actions.getASTContext().getPrintingPolicy()))
5349 Diag(StartLoc, DiagID) << PrevSpec;
5350 return;
5351 }
5352
5353 if (IsDependent) {
5354 // This enum has a dependent nested-name-specifier. Handle it as a
5355 // dependent tag.
5356 if (!Name) {
5357 DS.SetTypeSpecError();
5358 Diag(Tok, diag::err_expected_type_name_after_typename);
5359 return;
5360 }
5361
5362 TypeResult Type = Actions.ActOnDependentTag(
5363 getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
5364 if (Type.isInvalid()) {
5365 DS.SetTypeSpecError();
5366 return;
5367 }
5368
5369 if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
5370 NameLoc.isValid() ? NameLoc : StartLoc,
5371 PrevSpec, DiagID, Type.get(),
5372 Actions.getASTContext().getPrintingPolicy()))
5373 Diag(StartLoc, DiagID) << PrevSpec;
5374
5375 return;
5376 }
5377
5378 if (!TagDecl) {
5379 // The action failed to produce an enumeration tag. If this is a
5380 // definition, consume the entire definition.
5381 if (Tok.is(tok::l_brace) && TUK != TagUseKind::Reference) {
5382 ConsumeBrace();
5383 SkipUntil(tok::r_brace, StopAtSemi);
5384 }
5385
5386 DS.SetTypeSpecError();
5387 return;
5388 }
5389
5390 if (Tok.is(tok::l_brace) && TUK == TagUseKind::Definition) {
5391 Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
5392 ParseEnumBody(StartLoc, D, &SkipBody);
5393 if (SkipBody.CheckSameAsPrevious &&
5394 !Actions.ActOnDuplicateDefinition(getCurScope(), TagDecl, SkipBody)) {
5395 DS.SetTypeSpecError();
5396 return;
5397 }
5398 }
5399
5400 if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5401 NameLoc.isValid() ? NameLoc : StartLoc,
5402 PrevSpec, DiagID, TagDecl, Owned,
5403 Actions.getASTContext().getPrintingPolicy()))
5404 Diag(StartLoc, DiagID) << PrevSpec;
5405}
5406
5407void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl,
5408 SkipBodyInfo *SkipBody) {
5409 // Enter the scope of the enum body and start the definition.
5410 ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
5411 Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
5412
5413 BalancedDelimiterTracker T(*this, tok::l_brace);
5414 T.consumeOpen();
5415
5416 // C does not allow an empty enumerator-list, C++ does [dcl.enum].
5417 if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) {
5418 if (getLangOpts().MicrosoftExt)
5419 Diag(T.getOpenLocation(), diag::ext_ms_c_empty_enum_type)
5420 << SourceRange(T.getOpenLocation(), Tok.getLocation());
5421 else
5422 Diag(Tok, diag::err_empty_enum);
5423 }
5424
5425 SmallVector<Decl *, 32> EnumConstantDecls;
5426 SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
5427
5428 Decl *LastEnumConstDecl = nullptr;
5429
5430 // Parse the enumerator-list.
5431 while (Tok.isNot(tok::r_brace)) {
5432 // Parse enumerator. If failed, try skipping till the start of the next
5433 // enumerator definition.
5434 if (Tok.isNot(tok::identifier)) {
5435 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
5436 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
5437 TryConsumeToken(tok::comma))
5438 continue;
5439 break;
5440 }
5441 IdentifierInfo *Ident = Tok.getIdentifierInfo();
5442 SourceLocation IdentLoc = ConsumeToken();
5443
5444 // If attributes exist after the enumerator, parse them.
5445 ParsedAttributes attrs(AttrFactory);
5446 MaybeParseGNUAttributes(attrs);
5447 if (isAllowedCXX11AttributeSpecifier()) {
5448 if (getLangOpts().CPlusPlus)
5449 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
5450 ? diag::warn_cxx14_compat_ns_enum_attribute
5451 : diag::ext_ns_enum_attribute)
5452 << 1 /*enumerator*/;
5453 ParseCXX11Attributes(attrs);
5454 }
5455
5456 SourceLocation EqualLoc;
5457 ExprResult AssignedVal;
5458 EnumAvailabilityDiags.emplace_back(*this);
5459
5460 EnterExpressionEvaluationContext ConstantEvaluated(
5462 if (TryConsumeToken(tok::equal, EqualLoc)) {
5464 if (AssignedVal.isInvalid())
5465 SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
5466 }
5467
5468 // Install the enumerator constant into EnumDecl.
5469 Decl *EnumConstDecl = Actions.ActOnEnumConstant(
5470 getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
5471 EqualLoc, AssignedVal.get(), SkipBody);
5472 EnumAvailabilityDiags.back().done();
5473
5474 EnumConstantDecls.push_back(EnumConstDecl);
5475 LastEnumConstDecl = EnumConstDecl;
5476
5477 if (Tok.is(tok::identifier)) {
5478 // We're missing a comma between enumerators.
5479 SourceLocation Loc = getEndOfPreviousToken();
5480 Diag(Loc, diag::err_enumerator_list_missing_comma)
5481 << FixItHint::CreateInsertion(Loc, ", ");
5482 continue;
5483 }
5484
5485 // Emumerator definition must be finished, only comma or r_brace are
5486 // allowed here.
5487 SourceLocation CommaLoc;
5488 if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
5489 if (EqualLoc.isValid())
5490 Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
5491 << tok::comma;
5492 else
5493 Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
5494 if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
5495 if (TryConsumeToken(tok::comma, CommaLoc))
5496 continue;
5497 } else {
5498 break;
5499 }
5500 }
5501
5502 // If comma is followed by r_brace, emit appropriate warning.
5503 if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
5505 Diag(CommaLoc, getLangOpts().CPlusPlus ?
5506 diag::ext_enumerator_list_comma_cxx :
5507 diag::ext_enumerator_list_comma_c)
5508 << FixItHint::CreateRemoval(CommaLoc);
5509 else if (getLangOpts().CPlusPlus11)
5510 Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
5511 << FixItHint::CreateRemoval(CommaLoc);
5512 break;
5513 }
5514 }
5515
5516 // Eat the }.
5517 T.consumeClose();
5518
5519 // If attributes exist after the identifier list, parse them.
5520 ParsedAttributes attrs(AttrFactory);
5521 MaybeParseGNUAttributes(attrs);
5522
5523 Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
5524 getCurScope(), attrs);
5525
5526 // Now handle enum constant availability diagnostics.
5527 assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
5528 for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
5529 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
5530 EnumAvailabilityDiags[i].redelay();
5531 PD.complete(EnumConstantDecls[i]);
5532 }
5533
5534 EnumScope.Exit();
5535 Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
5536
5537 // The next token must be valid after an enum definition. If not, a ';'
5538 // was probably forgotten.
5539 bool CanBeBitfield = getCurScope()->isClassScope();
5540 if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
5541 ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5542 // Push this token back into the preprocessor and change our current token
5543 // to ';' so that the rest of the code recovers as though there were an
5544 // ';' after the definition.
5545 PP.EnterToken(Tok, /*IsReinject=*/true);
5546 Tok.setKind(tok::semi);
5547 }
5548}
5549
5550bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
5551 switch (Tok.getKind()) {
5552 default: return false;
5553 // type-specifiers
5554 case tok::kw_short:
5555 case tok::kw_long:
5556 case tok::kw___int64:
5557 case tok::kw___int128:
5558 case tok::kw_signed:
5559 case tok::kw_unsigned:
5560 case tok::kw__Complex:
5561 case tok::kw__Imaginary:
5562 case tok::kw_void:
5563 case tok::kw_char:
5564 case tok::kw_wchar_t:
5565 case tok::kw_char8_t:
5566 case tok::kw_char16_t:
5567 case tok::kw_char32_t:
5568 case tok::kw_int:
5569 case tok::kw__ExtInt:
5570 case tok::kw__BitInt:
5571 case tok::kw___bf16:
5572 case tok::kw_half:
5573 case tok::kw_float:
5574 case tok::kw_double:
5575 case tok::kw__Accum:
5576 case tok::kw__Fract:
5577 case tok::kw__Float16:
5578 case tok::kw___float128:
5579 case tok::kw___ibm128:
5580 case tok::kw_bool:
5581 case tok::kw__Bool:
5582 case tok::kw__Decimal32:
5583 case tok::kw__Decimal64:
5584 case tok::kw__Decimal128:
5585 case tok::kw___vector:
5586#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5587#include "clang/Basic/OpenCLImageTypes.def"
5588#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
5589#include "clang/Basic/HLSLIntangibleTypes.def"
5590
5591 // struct-or-union-specifier (C99) or class-specifier (C++)
5592 case tok::kw_class:
5593 case tok::kw_struct:
5594 case tok::kw___interface:
5595 case tok::kw_union:
5596 // enum-specifier
5597 case tok::kw_enum:
5598
5599 case tok::kw_typeof:
5600 case tok::kw_typeof_unqual:
5601
5602 // C11 _Atomic
5603 case tok::kw__Atomic:
5604
5605 // typedef-name
5606 case tok::annot_typename:
5607 return true;
5608 }
5609}
5610
5611bool Parser::isTypeSpecifierQualifier(const Token &Tok) {
5612 switch (Tok.getKind()) {
5613 default: return false;
5614
5615 case tok::identifier: // foo::bar
5616 if (TryAltiVecVectorToken())
5617 return true;
5618 [[fallthrough]];
5619 case tok::kw_typename: // typename T::type
5620 // Annotate typenames and C++ scope specifiers. If we get one, just
5621 // recurse to handle whatever we get.
5623 return true;
5624 if (getCurToken().is(tok::identifier))
5625 return false;
5626 return isTypeSpecifierQualifier(getCurToken());
5627
5628 case tok::coloncolon: // ::foo::bar
5629 if (NextToken().is(tok::kw_new) || // ::new
5630 NextToken().is(tok::kw_delete)) // ::delete
5631 return false;
5632
5634 return true;
5635 return isTypeSpecifierQualifier(getCurToken());
5636
5637 // GNU attributes support.
5638 case tok::kw___attribute:
5639 // C23/GNU typeof support.
5640 case tok::kw_typeof:
5641 case tok::kw_typeof_unqual:
5642
5643 // type-specifiers
5644 case tok::kw_short:
5645 case tok::kw_long:
5646 case tok::kw___int64:
5647 case tok::kw___int128:
5648 case tok::kw_signed:
5649 case tok::kw_unsigned:
5650 case tok::kw__Complex:
5651 case tok::kw__Imaginary:
5652 case tok::kw_void:
5653 case tok::kw_char:
5654 case tok::kw_wchar_t:
5655 case tok::kw_char8_t:
5656 case tok::kw_char16_t:
5657 case tok::kw_char32_t:
5658 case tok::kw_int:
5659 case tok::kw__ExtInt:
5660 case tok::kw__BitInt:
5661 case tok::kw_half:
5662 case tok::kw___bf16:
5663 case tok::kw_float:
5664 case tok::kw_double:
5665 case tok::kw__Accum:
5666 case tok::kw__Fract:
5667 case tok::kw__Float16:
5668 case tok::kw___float128:
5669 case tok::kw___ibm128:
5670 case tok::kw_bool:
5671 case tok::kw__Bool:
5672 case tok::kw__Decimal32:
5673 case tok::kw__Decimal64:
5674 case tok::kw__Decimal128:
5675 case tok::kw___vector:
5676#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5677#include "clang/Basic/OpenCLImageTypes.def"
5678#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
5679#include "clang/Basic/HLSLIntangibleTypes.def"
5680
5681 // struct-or-union-specifier (C99) or class-specifier (C++)
5682 case tok::kw_class:
5683 case tok::kw_struct:
5684 case tok::kw___interface:
5685 case tok::kw_union:
5686 // enum-specifier
5687 case tok::kw_enum:
5688
5689 // type-qualifier
5690 case tok::kw_const:
5691 case tok::kw_volatile:
5692 case tok::kw_restrict:
5693 case tok::kw___ob_wrap:
5694 case tok::kw___ob_trap:
5695 case tok::kw__Sat:
5696
5697 // Debugger support.
5698 case tok::kw___unknown_anytype:
5699
5700 // typedef-name
5701 case tok::annot_typename:
5702 return true;
5703
5704 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5705 case tok::less:
5706 return getLangOpts().ObjC;
5707
5708 case tok::kw___cdecl:
5709 case tok::kw___stdcall:
5710 case tok::kw___fastcall:
5711 case tok::kw___thiscall:
5712 case tok::kw___regcall:
5713 case tok::kw___vectorcall:
5714 case tok::kw___w64:
5715 case tok::kw___ptr64:
5716 case tok::kw___ptr32:
5717 case tok::kw___pascal:
5718 case tok::kw___unaligned:
5719 case tok::kw___ptrauth:
5720
5721 case tok::kw__Nonnull:
5722 case tok::kw__Nullable:
5723 case tok::kw__Nullable_result:
5724 case tok::kw__Null_unspecified:
5725
5726 case tok::kw___kindof:
5727
5728 case tok::kw___private:
5729 case tok::kw___local:
5730 case tok::kw___global:
5731 case tok::kw___constant:
5732 case tok::kw___generic:
5733 case tok::kw___read_only:
5734 case tok::kw___read_write:
5735 case tok::kw___write_only:
5736 case tok::kw___funcref:
5737 return true;
5738
5739 case tok::kw_private:
5740 return getLangOpts().OpenCL;
5741
5742 // C11 _Atomic
5743 case tok::kw__Atomic:
5744 return true;
5745
5746 // HLSL type qualifiers
5747 case tok::kw_groupshared:
5748 case tok::kw_in:
5749 case tok::kw_inout:
5750 case tok::kw_out:
5751 return getLangOpts().HLSL;
5752 }
5753}
5754
5755Parser::DeclGroupPtrTy Parser::ParseTopLevelStmtDecl() {
5756 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode");
5757
5758 // Parse a top-level-stmt.
5759 Parser::StmtVector Stmts;
5760 ParsedStmtContext SubStmtCtx = ParsedStmtContext();
5763 TopLevelStmtDecl *TLSD = Actions.ActOnStartTopLevelStmtDecl(getCurScope());
5764 StmtResult R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
5765 Actions.ActOnFinishTopLevelStmtDecl(TLSD, R.get());
5766 if (!R.isUsable())
5767 R = Actions.ActOnNullStmt(Tok.getLocation());
5768
5769 if (Tok.is(tok::annot_repl_input_end) &&
5770 Tok.getAnnotationValue() != nullptr) {
5771 ConsumeAnnotationToken();
5772 TLSD->setSemiMissing();
5773 }
5774
5775 SmallVector<Decl *, 2> DeclsInGroup;
5776 DeclsInGroup.push_back(TLSD);
5777
5778 // Currently happens for things like -fms-extensions and use `__if_exists`.
5779 for (Stmt *S : Stmts) {
5780 // Here we should be safe as `__if_exists` and friends are not introducing
5781 // new variables which need to live outside file scope.
5782 TopLevelStmtDecl *D = Actions.ActOnStartTopLevelStmtDecl(getCurScope());
5783 Actions.ActOnFinishTopLevelStmtDecl(D, S);
5784 DeclsInGroup.push_back(D);
5785 }
5786
5787 return Actions.BuildDeclaratorGroup(DeclsInGroup);
5788}
5789
5790bool Parser::isDeclarationSpecifier(
5791 ImplicitTypenameContext AllowImplicitTypename,
5792 bool DisambiguatingWithExpression) {
5793 switch (Tok.getKind()) {
5794 default: return false;
5795
5796 // OpenCL 2.0 and later define this keyword.
5797 case tok::kw_pipe:
5798 return getLangOpts().OpenCL &&
5800
5801 case tok::identifier: // foo::bar
5802 // Unfortunate hack to support "Class.factoryMethod" notation.
5803 if (getLangOpts().ObjC && NextToken().is(tok::period))
5804 return false;
5805 if (TryAltiVecVectorToken())
5806 return true;
5807 [[fallthrough]];
5808 case tok::kw_decltype: // decltype(T())::type
5809 case tok::kw_typename: // typename T::type
5810 // Annotate typenames and C++ scope specifiers. If we get one, just
5811 // recurse to handle whatever we get.
5812 if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
5813 return true;
5814 if (TryAnnotateTypeConstraint())
5815 return true;
5816 if (Tok.is(tok::identifier))
5817 return false;
5818
5819 // If we're in Objective-C and we have an Objective-C class type followed
5820 // by an identifier and then either ':' or ']', in a place where an
5821 // expression is permitted, then this is probably a class message send
5822 // missing the initial '['. In this case, we won't consider this to be
5823 // the start of a declaration.
5824 if (DisambiguatingWithExpression &&
5825 isStartOfObjCClassMessageMissingOpenBracket())
5826 return false;
5827
5828 return isDeclarationSpecifier(AllowImplicitTypename);
5829
5830 case tok::coloncolon: // ::foo::bar
5831 if (!getLangOpts().CPlusPlus)
5832 return false;
5833 if (NextToken().is(tok::kw_new) || // ::new
5834 NextToken().is(tok::kw_delete)) // ::delete
5835 return false;
5836
5837 // Annotate typenames and C++ scope specifiers. If we get one, just
5838 // recurse to handle whatever we get.
5840 return true;
5841 return isDeclarationSpecifier(ImplicitTypenameContext::No);
5842
5843 // storage-class-specifier
5844 case tok::kw_typedef:
5845 case tok::kw_extern:
5846 case tok::kw___private_extern__:
5847 case tok::kw_static:
5848 case tok::kw_auto:
5849 case tok::kw___auto_type:
5850 case tok::kw_register:
5851 case tok::kw___thread:
5852 case tok::kw_thread_local:
5853 case tok::kw__Thread_local:
5854
5855 // Modules
5856 case tok::kw___module_private__:
5857
5858 // Debugger support
5859 case tok::kw___unknown_anytype:
5860
5861 // type-specifiers
5862 case tok::kw_short:
5863 case tok::kw_long:
5864 case tok::kw___int64:
5865 case tok::kw___int128:
5866 case tok::kw_signed:
5867 case tok::kw_unsigned:
5868 case tok::kw__Complex:
5869 case tok::kw__Imaginary:
5870 case tok::kw_void:
5871 case tok::kw_char:
5872 case tok::kw_wchar_t:
5873 case tok::kw_char8_t:
5874 case tok::kw_char16_t:
5875 case tok::kw_char32_t:
5876
5877 case tok::kw_int:
5878 case tok::kw__ExtInt:
5879 case tok::kw__BitInt:
5880 case tok::kw_half:
5881 case tok::kw___bf16:
5882 case tok::kw_float:
5883 case tok::kw_double:
5884 case tok::kw__Accum:
5885 case tok::kw__Fract:
5886 case tok::kw__Float16:
5887 case tok::kw___float128:
5888 case tok::kw___ibm128:
5889 case tok::kw_bool:
5890 case tok::kw__Bool:
5891 case tok::kw__Decimal32:
5892 case tok::kw__Decimal64:
5893 case tok::kw__Decimal128:
5894 case tok::kw___vector:
5895
5896 // struct-or-union-specifier (C99) or class-specifier (C++)
5897 case tok::kw_class:
5898 case tok::kw_struct:
5899 case tok::kw_union:
5900 case tok::kw___interface:
5901 // enum-specifier
5902 case tok::kw_enum:
5903
5904 // type-qualifier
5905 case tok::kw_const:
5906 case tok::kw_volatile:
5907 case tok::kw_restrict:
5908 case tok::kw___ob_wrap:
5909 case tok::kw___ob_trap:
5910 case tok::kw__Sat:
5911
5912 // function-specifier
5913 case tok::kw_inline:
5914 case tok::kw_virtual:
5915 case tok::kw_explicit:
5916 case tok::kw__Noreturn:
5917
5918 // alignment-specifier
5919 case tok::kw__Alignas:
5920
5921 // friend keyword.
5922 case tok::kw_friend:
5923
5924 // static_assert-declaration
5925 case tok::kw_static_assert:
5926 case tok::kw__Static_assert:
5927
5928 // C23/GNU typeof support.
5929 case tok::kw_typeof:
5930 case tok::kw_typeof_unqual:
5931
5932 // GNU attributes.
5933 case tok::kw___attribute:
5934
5935 // C++11 decltype and constexpr.
5936 case tok::annot_decltype:
5937 case tok::annot_pack_indexing_type:
5938 case tok::kw_constexpr:
5939
5940 // C++20 consteval and constinit.
5941 case tok::kw_consteval:
5942 case tok::kw_constinit:
5943
5944 // C11 _Atomic
5945 case tok::kw__Atomic:
5946 return true;
5947
5948 case tok::kw_alignas:
5949 // alignas is a type-specifier-qualifier in C23, which is a kind of
5950 // declaration-specifier. Outside of C23 mode (including in C++), it is not.
5951 return getLangOpts().C23;
5952
5953 // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5954 case tok::less:
5955 return getLangOpts().ObjC;
5956
5957 // typedef-name
5958 case tok::annot_typename:
5959 return !DisambiguatingWithExpression ||
5960 !isStartOfObjCClassMessageMissingOpenBracket();
5961
5962 // placeholder-type-specifier
5963 case tok::annot_template_id: {
5964 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
5965 if (TemplateId->hasInvalidName())
5966 return true;
5967 // FIXME: What about type templates that have only been annotated as
5968 // annot_template_id, not as annot_typename?
5969 return isTypeConstraintAnnotation() &&
5970 (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
5971 }
5972
5973 case tok::annot_cxxscope: {
5974 TemplateIdAnnotation *TemplateId =
5975 NextToken().is(tok::annot_template_id)
5976 ? takeTemplateIdAnnotation(NextToken())
5977 : nullptr;
5978 if (TemplateId && TemplateId->hasInvalidName())
5979 return true;
5980 // FIXME: What about type templates that have only been annotated as
5981 // annot_template_id, not as annot_typename?
5982 if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
5983 return true;
5984 return isTypeConstraintAnnotation() &&
5985 GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
5986 }
5987
5988 case tok::kw___declspec:
5989 case tok::kw___cdecl:
5990 case tok::kw___stdcall:
5991 case tok::kw___fastcall:
5992 case tok::kw___thiscall:
5993 case tok::kw___regcall:
5994 case tok::kw___vectorcall:
5995 case tok::kw___w64:
5996 case tok::kw___sptr:
5997 case tok::kw___uptr:
5998 case tok::kw___ptr64:
5999 case tok::kw___ptr32:
6000 case tok::kw___forceinline:
6001 case tok::kw___pascal:
6002 case tok::kw___unaligned:
6003 case tok::kw___ptrauth:
6004
6005 case tok::kw__Nonnull:
6006 case tok::kw__Nullable:
6007 case tok::kw__Nullable_result:
6008 case tok::kw__Null_unspecified:
6009
6010 case tok::kw___kindof:
6011
6012 case tok::kw___private:
6013 case tok::kw___local:
6014 case tok::kw___global:
6015 case tok::kw___constant:
6016 case tok::kw___generic:
6017 case tok::kw___read_only:
6018 case tok::kw___read_write:
6019 case tok::kw___write_only:
6020#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
6021#include "clang/Basic/OpenCLImageTypes.def"
6022#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
6023#include "clang/Basic/HLSLIntangibleTypes.def"
6024
6025 case tok::kw___funcref:
6026 case tok::kw_groupshared:
6027 return true;
6028
6029 case tok::kw_private:
6030 return getLangOpts().OpenCL;
6031 }
6032}
6033
6034bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide,
6036 const ParsedTemplateInfo *TemplateInfo) {
6037 RevertingTentativeParsingAction TPA(*this);
6038 // Parse the C++ scope specifier.
6039 CXXScopeSpec SS;
6040 if (TemplateInfo && TemplateInfo->TemplateParams)
6041 SS.setTemplateParamLists(*TemplateInfo->TemplateParams);
6042
6043 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6044 /*ObjectHasErrors=*/false,
6045 /*EnteringContext=*/true)) {
6046 return false;
6047 }
6048
6049 // Parse the constructor name.
6050 if (Tok.is(tok::identifier)) {
6051 // We already know that we have a constructor name; just consume
6052 // the token.
6053 ConsumeToken();
6054 } else if (Tok.is(tok::annot_template_id)) {
6055 ConsumeAnnotationToken();
6056 } else {
6057 return false;
6058 }
6059
6060 // There may be attributes here, appertaining to the constructor name or type
6061 // we just stepped past.
6062 SkipCXX11Attributes();
6063
6064 // Current class name must be followed by a left parenthesis.
6065 if (Tok.isNot(tok::l_paren)) {
6066 return false;
6067 }
6068 ConsumeParen();
6069
6070 // A right parenthesis, or ellipsis followed by a right parenthesis signals
6071 // that we have a constructor.
6072 if (Tok.is(tok::r_paren) ||
6073 (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
6074 return true;
6075 }
6076
6077 // A C++11 attribute here signals that we have a constructor, and is an
6078 // attribute on the first constructor parameter.
6079 if (isCXX11AttributeSpecifier(/*Disambiguate=*/false,
6080 /*OuterMightBeMessageSend=*/true) !=
6082 return true;
6083 }
6084
6085 // If we need to, enter the specified scope.
6086 DeclaratorScopeObj DeclScopeObj(*this, SS);
6087 if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
6088 DeclScopeObj.EnterDeclaratorScope();
6089
6090 // Optionally skip Microsoft attributes.
6091 ParsedAttributes Attrs(AttrFactory);
6092 MaybeParseMicrosoftAttributes(Attrs);
6093
6094 // Check whether the next token(s) are part of a declaration
6095 // specifier, in which case we have the start of a parameter and,
6096 // therefore, we know that this is a constructor.
6097 // Due to an ambiguity with implicit typename, the above is not enough.
6098 // Additionally, check to see if we are a friend.
6099 // If we parsed a scope specifier as well as friend,
6100 // we might be parsing a friend constructor.
6101 bool IsConstructor = false;
6102 ImplicitTypenameContext ITC = IsFriend && !SS.isSet()
6105 // Constructors cannot have this parameters, but we support that scenario here
6106 // to improve diagnostic.
6107 if (Tok.is(tok::kw_this)) {
6108 ConsumeToken();
6109 return isDeclarationSpecifier(ITC);
6110 }
6111
6112 if (isDeclarationSpecifier(ITC))
6113 IsConstructor = true;
6114 else if (Tok.is(tok::identifier) ||
6115 (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
6116 // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
6117 // This might be a parenthesized member name, but is more likely to
6118 // be a constructor declaration with an invalid argument type. Keep
6119 // looking.
6120 if (Tok.is(tok::annot_cxxscope))
6121 ConsumeAnnotationToken();
6122 ConsumeToken();
6123
6124 // If this is not a constructor, we must be parsing a declarator,
6125 // which must have one of the following syntactic forms (see the
6126 // grammar extract at the start of ParseDirectDeclarator):
6127 switch (Tok.getKind()) {
6128 case tok::l_paren:
6129 // C(X ( int));
6130 case tok::l_square:
6131 // C(X [ 5]);
6132 // C(X [ [attribute]]);
6133 case tok::coloncolon:
6134 // C(X :: Y);
6135 // C(X :: *p);
6136 // Assume this isn't a constructor, rather than assuming it's a
6137 // constructor with an unnamed parameter of an ill-formed type.
6138 break;
6139
6140 case tok::r_paren:
6141 // C(X )
6142
6143 // Skip past the right-paren and any following attributes to get to
6144 // the function body or trailing-return-type.
6145 ConsumeParen();
6146 SkipCXX11Attributes();
6147
6148 if (DeductionGuide) {
6149 // C(X) -> ... is a deduction guide.
6150 IsConstructor = Tok.is(tok::arrow);
6151 break;
6152 }
6153 if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
6154 // Assume these were meant to be constructors:
6155 // C(X) : (the name of a bit-field cannot be parenthesized).
6156 // C(X) try (this is otherwise ill-formed).
6157 IsConstructor = true;
6158 }
6159 if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
6160 // If we have a constructor name within the class definition,
6161 // assume these were meant to be constructors:
6162 // C(X) {
6163 // C(X) ;
6164 // ... because otherwise we would be declaring a non-static data
6165 // member that is ill-formed because it's of the same type as its
6166 // surrounding class.
6167 //
6168 // FIXME: We can actually do this whether or not the name is qualified,
6169 // because if it is qualified in this context it must be being used as
6170 // a constructor name.
6171 // currently, so we're somewhat conservative here.
6172 IsConstructor = IsUnqualified;
6173 }
6174 break;
6175
6176 default:
6177 IsConstructor = true;
6178 break;
6179 }
6180 }
6181 return IsConstructor;
6182}
6183
6184void Parser::ParseTypeQualifierListOpt(
6185 DeclSpec &DS, unsigned AttrReqs, bool AtomicOrPtrauthAllowed,
6186 bool IdentifierRequired, llvm::function_ref<void()> CodeCompletionHandler) {
6187 if ((AttrReqs & AR_CXX11AttributesParsed) &&
6188 isAllowedCXX11AttributeSpecifier()) {
6189 ParsedAttributes Attrs(AttrFactory);
6190 ParseCXX11Attributes(Attrs);
6192 }
6193
6194 SourceLocation EndLoc;
6195
6196 while (true) {
6197 bool isInvalid = false;
6198 const char *PrevSpec = nullptr;
6199 unsigned DiagID = 0;
6200 SourceLocation Loc = Tok.getLocation();
6201
6202 switch (Tok.getKind()) {
6203 case tok::code_completion:
6204 cutOffParsing();
6205 if (CodeCompletionHandler)
6206 CodeCompletionHandler();
6207 else
6208 Actions.CodeCompletion().CodeCompleteTypeQualifiers(DS);
6209 return;
6210
6211 case tok::kw_const:
6212 isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
6213 getLangOpts());
6214 break;
6215 case tok::kw_volatile:
6216 isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
6217 getLangOpts());
6218 break;
6219 case tok::kw_restrict:
6220 isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
6221 getLangOpts());
6222 break;
6223 case tok::kw___ob_wrap:
6224 if (!getLangOpts().OverflowBehaviorTypes) {
6225 Diag(Loc, diag::warn_overflow_behavior_keyword_disabled)
6226 << tok::getKeywordSpelling(Tok.getKind());
6227 break;
6228 }
6230 OverflowBehaviorType::OverflowBehaviorKind::Wrap, Loc, PrevSpec,
6231 DiagID);
6232 break;
6233 case tok::kw___ob_trap:
6234 if (!getLangOpts().OverflowBehaviorTypes) {
6235 Diag(Loc, diag::warn_overflow_behavior_keyword_disabled)
6236 << tok::getKeywordSpelling(Tok.getKind());
6237 break;
6238 }
6240 OverflowBehaviorType::OverflowBehaviorKind::Trap, Loc, PrevSpec,
6241 DiagID);
6242 break;
6243 case tok::kw__Atomic:
6244 if (!AtomicOrPtrauthAllowed)
6245 goto DoneWithTypeQuals;
6246 diagnoseUseOfC11Keyword(Tok);
6247 isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
6248 getLangOpts());
6249 break;
6250
6251 // OpenCL qualifiers:
6252 case tok::kw_private:
6253 if (!getLangOpts().OpenCL)
6254 goto DoneWithTypeQuals;
6255 [[fallthrough]];
6256 case tok::kw___private:
6257 case tok::kw___global:
6258 case tok::kw___local:
6259 case tok::kw___constant:
6260 case tok::kw___generic:
6261 case tok::kw___read_only:
6262 case tok::kw___write_only:
6263 case tok::kw___read_write:
6264 ParseOpenCLQualifiers(DS.getAttributes());
6265 break;
6266
6267 case tok::kw_groupshared:
6268 case tok::kw_in:
6269 case tok::kw_inout:
6270 case tok::kw_out:
6271 // NOTE: ParseHLSLQualifiers will consume the qualifier token.
6272 ParseHLSLQualifiers(DS.getAttributes());
6273 continue;
6274
6275 // __ptrauth qualifier.
6276 case tok::kw___ptrauth:
6277 if (!AtomicOrPtrauthAllowed)
6278 goto DoneWithTypeQuals;
6279 ParsePtrauthQualifier(DS.getAttributes());
6280 EndLoc = PrevTokLocation;
6281 continue;
6282
6283 case tok::kw___unaligned:
6284 isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
6285 getLangOpts());
6286 break;
6287 case tok::kw___uptr:
6288 // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
6289 // with the MS modifier keyword.
6290 if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
6291 IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
6292 if (TryKeywordIdentFallback(false))
6293 continue;
6294 }
6295 [[fallthrough]];
6296 case tok::kw___sptr:
6297 case tok::kw___w64:
6298 case tok::kw___ptr64:
6299 case tok::kw___ptr32:
6300 case tok::kw___cdecl:
6301 case tok::kw___stdcall:
6302 case tok::kw___fastcall:
6303 case tok::kw___thiscall:
6304 case tok::kw___regcall:
6305 case tok::kw___vectorcall:
6306 if (AttrReqs & AR_DeclspecAttributesParsed) {
6307 ParseMicrosoftTypeAttributes(DS.getAttributes());
6308 continue;
6309 }
6310 goto DoneWithTypeQuals;
6311
6312 case tok::kw___funcref:
6313 ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());
6314 continue;
6315
6316 case tok::kw___pascal:
6317 if (AttrReqs & AR_VendorAttributesParsed) {
6318 ParseBorlandTypeAttributes(DS.getAttributes());
6319 continue;
6320 }
6321 goto DoneWithTypeQuals;
6322
6323 // Nullability type specifiers.
6324 case tok::kw__Nonnull:
6325 case tok::kw__Nullable:
6326 case tok::kw__Nullable_result:
6327 case tok::kw__Null_unspecified:
6328 ParseNullabilityTypeSpecifiers(DS.getAttributes());
6329 continue;
6330
6331 // Objective-C 'kindof' types.
6332 case tok::kw___kindof:
6333 DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc,
6334 AttributeScopeInfo(), nullptr, 0,
6335 tok::kw___kindof);
6336 (void)ConsumeToken();
6337 continue;
6338
6339 case tok::kw___attribute:
6340 if (AttrReqs & AR_GNUAttributesParsedAndRejected)
6341 // When GNU attributes are expressly forbidden, diagnose their usage.
6342 Diag(Tok, diag::err_attributes_not_allowed);
6343
6344 // Parse the attributes even if they are rejected to ensure that error
6345 // recovery is graceful.
6346 if (AttrReqs & AR_GNUAttributesParsed ||
6347 AttrReqs & AR_GNUAttributesParsedAndRejected) {
6348 ParseGNUAttributes(DS.getAttributes());
6349 continue; // do *not* consume the next token!
6350 }
6351 // otherwise, FALL THROUGH!
6352 [[fallthrough]];
6353 default:
6354 DoneWithTypeQuals:
6355 // If this is not a type-qualifier token, we're done reading type
6356 // qualifiers. First verify that DeclSpec's are consistent.
6357 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
6358 if (EndLoc.isValid())
6359 DS.SetRangeEnd(EndLoc);
6360 return;
6361 }
6362
6363 // If the specifier combination wasn't legal, issue a diagnostic.
6364 if (isInvalid) {
6365 assert(PrevSpec && "Method did not return previous specifier!");
6366 Diag(Tok, DiagID) << PrevSpec;
6367 }
6368 EndLoc = ConsumeToken();
6369 }
6370}
6371
6372void Parser::ParseDeclarator(Declarator &D) {
6373 /// This implements the 'declarator' production in the C grammar, then checks
6374 /// for well-formedness and issues diagnostics.
6375 Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
6376 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6377 });
6378}
6379
6380static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
6381 DeclaratorContext TheContext) {
6382 if (Kind == tok::star || Kind == tok::caret)
6383 return true;
6384
6385 // OpenCL 2.0 and later define this keyword.
6386 if (Kind == tok::kw_pipe && Lang.OpenCL &&
6387 Lang.getOpenCLCompatibleVersion() >= 200)
6388 return true;
6389
6390 if (!Lang.CPlusPlus)
6391 return false;
6392
6393 if (Kind == tok::amp)
6394 return true;
6395
6396 // We parse rvalue refs in C++03, because otherwise the errors are scary.
6397 // But we must not parse them in conversion-type-ids and new-type-ids, since
6398 // those can be legitimately followed by a && operator.
6399 // (The same thing can in theory happen after a trailing-return-type, but
6400 // since those are a C++11 feature, there is no rejects-valid issue there.)
6401 if (Kind == tok::ampamp)
6402 return Lang.CPlusPlus11 || (TheContext != DeclaratorContext::ConversionId &&
6403 TheContext != DeclaratorContext::CXXNew);
6404
6405 return false;
6406}
6407
6408// Indicates whether the given declarator is a pipe declarator.
6409static bool isPipeDeclarator(const Declarator &D) {
6410 const unsigned NumTypes = D.getNumTypeObjects();
6411
6412 for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
6414 return true;
6415
6416 return false;
6417}
6418
6419void Parser::ParseDeclaratorInternal(Declarator &D,
6420 DirectDeclParseFunction DirectDeclParser) {
6421 if (Diags.hasAllExtensionsSilenced())
6422 D.setExtension();
6423
6424 // C++ member pointers start with a '::' or a nested-name.
6425 // Member pointers get special handling, since there's no place for the
6426 // scope spec in the generic path below.
6427 if (getLangOpts().CPlusPlus &&
6428 (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
6429 (Tok.is(tok::identifier) &&
6430 (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
6431 Tok.is(tok::annot_cxxscope))) {
6432 TentativeParsingAction TPA(*this, /*Unannotated=*/true);
6433 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6435 CXXScopeSpec SS;
6437
6438 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6439 /*ObjectHasErrors=*/false,
6440 /*EnteringContext=*/false,
6441 /*MayBePseudoDestructor=*/nullptr,
6442 /*IsTypename=*/false, /*LastII=*/nullptr,
6443 /*OnlyNamespace=*/false,
6444 /*InUsingDeclaration=*/false,
6445 /*Disambiguation=*/EnteringContext,
6446 /*IsAddressOfOperand=*/false,
6447 /*IsInDeclarationContext=*/true) ||
6448
6449 SS.isEmpty() || SS.isInvalid() || !EnteringContext ||
6450 Tok.is(tok::star)) {
6451 TPA.Commit();
6452 if (SS.isNotEmpty() && Tok.is(tok::star)) {
6453 if (SS.isValid()) {
6454 checkCompoundToken(SS.getEndLoc(), tok::coloncolon,
6455 CompoundToken::MemberPtr);
6456 }
6457
6458 SourceLocation StarLoc = ConsumeToken();
6459 D.SetRangeEnd(StarLoc);
6460 DeclSpec DS(AttrFactory);
6461 ParseTypeQualifierListOpt(DS);
6462 D.ExtendWithDeclSpec(DS);
6463
6464 // Recurse to parse whatever is left.
6465 Actions.runWithSufficientStackSpace(D.getBeginLoc(), [&] {
6466 ParseDeclaratorInternal(D, DirectDeclParser);
6467 });
6468
6469 // Sema will have to catch (syntactically invalid) pointers into global
6470 // scope. It has to catch pointers into namespace scope anyway.
6472 SS, DS.getTypeQualifiers(), StarLoc, DS.getEndLoc()),
6473 std::move(DS.getAttributes()),
6474 /*EndLoc=*/SourceLocation());
6475 return;
6476 }
6477 } else {
6478 TPA.Revert();
6479 SS.clear();
6480 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
6481 /*ObjectHasErrors=*/false,
6482 /*EnteringContext=*/true);
6483 }
6484
6485 if (SS.isNotEmpty()) {
6486 // The scope spec really belongs to the direct-declarator.
6487 if (D.mayHaveIdentifier())
6488 D.getCXXScopeSpec() = std::move(SS);
6489 else
6490 AnnotateScopeToken(SS, true);
6491
6492 if (DirectDeclParser)
6493 (this->*DirectDeclParser)(D);
6494 return;
6495 }
6496 }
6497
6498 tok::TokenKind Kind = Tok.getKind();
6499
6500 if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclarator(D)) {
6501 DeclSpec DS(AttrFactory);
6502 ParseTypeQualifierListOpt(DS);
6503
6504 D.AddTypeInfo(
6506 std::move(DS.getAttributes()), SourceLocation());
6507 }
6508
6509 // Not a pointer, C++ reference, or block.
6510 if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
6511 if (DirectDeclParser)
6512 (this->*DirectDeclParser)(D);
6513 return;
6514 }
6515
6516 // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
6517 // '&&' -> rvalue reference
6518 SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
6519 D.SetRangeEnd(Loc);
6520
6521 if (Kind == tok::star || Kind == tok::caret) {
6522 // Is a pointer.
6523 DeclSpec DS(AttrFactory);
6524
6525 // GNU attributes are not allowed here in a new-type-id, but Declspec and
6526 // C++11 attributes are allowed.
6527 unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
6529 ? AR_GNUAttributesParsed
6530 : AR_GNUAttributesParsedAndRejected);
6531 ParseTypeQualifierListOpt(DS, Reqs, /*AtomicOrPtrauthAllowed=*/true,
6532 !D.mayOmitIdentifier());
6533 D.ExtendWithDeclSpec(DS);
6534
6535 // Recursively parse the declarator.
6536 Actions.runWithSufficientStackSpace(
6537 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6538 if (Kind == tok::star)
6539 // Remember that we parsed a pointer type, and remember the type-quals.
6541 DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
6545 std::move(DS.getAttributes()), SourceLocation());
6546 else
6547 // Remember that we parsed a Block type, and remember the type-quals.
6548 D.AddTypeInfo(
6550 std::move(DS.getAttributes()), SourceLocation());
6551 } else {
6552 // Is a reference
6553 DeclSpec DS(AttrFactory);
6554
6555 // Complain about rvalue references in C++03, but then go on and build
6556 // the declarator.
6557 if (Kind == tok::ampamp)
6559 diag::warn_cxx98_compat_rvalue_reference :
6560 diag::ext_rvalue_reference);
6561
6562 // GNU-style and C++11 attributes are allowed here, as is restrict.
6563 ParseTypeQualifierListOpt(DS);
6564 D.ExtendWithDeclSpec(DS);
6565
6566 // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
6567 // cv-qualifiers are introduced through the use of a typedef or of a
6568 // template type argument, in which case the cv-qualifiers are ignored.
6571 Diag(DS.getConstSpecLoc(),
6572 diag::err_invalid_reference_qualifier_application) << "const";
6575 diag::err_invalid_reference_qualifier_application) << "volatile";
6576 // 'restrict' is permitted as an extension.
6579 diag::err_invalid_reference_qualifier_application) << "_Atomic";
6580 }
6581
6582 // Recursively parse the declarator.
6583 Actions.runWithSufficientStackSpace(
6584 D.getBeginLoc(), [&] { ParseDeclaratorInternal(D, DirectDeclParser); });
6585
6586 if (D.getNumTypeObjects() > 0) {
6587 // C++ [dcl.ref]p4: There shall be no references to references.
6588 DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
6589 if (InnerChunk.Kind == DeclaratorChunk::Reference) {
6590 if (const IdentifierInfo *II = D.getIdentifier())
6591 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6592 << II;
6593 else
6594 Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
6595 << "type name";
6596
6597 // Once we've complained about the reference-to-reference, we
6598 // can go ahead and build the (technically ill-formed)
6599 // declarator: reference collapsing will take care of it.
6600 }
6601 }
6602
6603 // Remember that we parsed a reference type.
6605 Kind == tok::amp),
6606 std::move(DS.getAttributes()), SourceLocation());
6607 }
6608}
6609
6610// When correcting from misplaced brackets before the identifier, the location
6611// is saved inside the declarator so that other diagnostic messages can use
6612// them. This extracts and returns that location, or returns the provided
6613// location if a stored location does not exist.
6615 SourceLocation Loc) {
6616 if (D.getName().StartLocation.isInvalid() &&
6618 return D.getName().EndLocation;
6619
6620 return Loc;
6621}
6622
6623void Parser::ParseDirectDeclarator(Declarator &D) {
6624 DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
6625
6627 // This might be a C++17 structured binding.
6628 if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
6630 return ParseDecompositionDeclarator(D);
6631
6632 // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
6633 // this context it is a bitfield. Also in range-based for statement colon
6634 // may delimit for-range-declaration.
6636 *this, D.getContext() == DeclaratorContext::Member ||
6639
6640 // ParseDeclaratorInternal might already have parsed the scope.
6641 if (D.getCXXScopeSpec().isEmpty()) {
6642 bool EnteringContext = D.getContext() == DeclaratorContext::File ||
6644 ParseOptionalCXXScopeSpecifier(
6645 D.getCXXScopeSpec(), /*ObjectType=*/nullptr,
6646 /*ObjectHasErrors=*/false, EnteringContext);
6647 }
6648
6649 // C++23 [basic.scope.namespace]p1:
6650 // For each non-friend redeclaration or specialization whose target scope
6651 // is or is contained by the scope, the portion after the declarator-id,
6652 // class-head-name, or enum-head-name is also included in the scope.
6653 // C++23 [basic.scope.class]p1:
6654 // For each non-friend redeclaration or specialization whose target scope
6655 // is or is contained by the scope, the portion after the declarator-id,
6656 // class-head-name, or enum-head-name is also included in the scope.
6657 //
6658 // FIXME: We should not be doing this for friend declarations; they have
6659 // their own special lookup semantics specified by [basic.lookup.unqual]p6.
6660 if (D.getCXXScopeSpec().isValid()) {
6661 if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
6662 D.getCXXScopeSpec()))
6663 // Change the declaration context for name lookup, until this function
6664 // is exited (and the declarator has been parsed).
6665 DeclScopeObj.EnterDeclaratorScope();
6666 else if (getObjCDeclContext()) {
6667 // Ensure that we don't interpret the next token as an identifier when
6668 // dealing with declarations in an Objective-C container.
6669 D.SetIdentifier(nullptr, Tok.getLocation());
6670 D.setInvalidType(true);
6671 ConsumeToken();
6672 goto PastIdentifier;
6673 }
6674 }
6675
6676 // C++0x [dcl.fct]p14:
6677 // There is a syntactic ambiguity when an ellipsis occurs at the end of a
6678 // parameter-declaration-clause without a preceding comma. In this case,
6679 // the ellipsis is parsed as part of the abstract-declarator if the type
6680 // of the parameter either names a template parameter pack that has not
6681 // been expanded or contains auto; otherwise, it is parsed as part of the
6682 // parameter-declaration-clause.
6683 if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
6687 NextToken().is(tok::r_paren) && !D.hasGroupingParens() &&
6688 !Actions.containsUnexpandedParameterPacks(D) &&
6690 SourceLocation EllipsisLoc = ConsumeToken();
6691 if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
6692 // The ellipsis was put in the wrong place. Recover, and explain to
6693 // the user what they should have done.
6694 ParseDeclarator(D);
6695 if (EllipsisLoc.isValid())
6696 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6697 return;
6698 } else
6699 D.setEllipsisLoc(EllipsisLoc);
6700
6701 // The ellipsis can't be followed by a parenthesized declarator. We
6702 // check for that in ParseParenDeclarator, after we have disambiguated
6703 // the l_paren token.
6704 }
6705
6706 if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
6707 tok::tilde)) {
6708 // We found something that indicates the start of an unqualified-id.
6709 // Parse that unqualified-id.
6710 bool AllowConstructorName;
6711 bool AllowDeductionGuide;
6712 if (D.getDeclSpec().hasTypeSpecifier()) {
6713 AllowConstructorName = false;
6714 AllowDeductionGuide = false;
6715 } else if (D.getCXXScopeSpec().isSet()) {
6716 AllowConstructorName = (D.getContext() == DeclaratorContext::File ||
6718 AllowDeductionGuide = false;
6719 } else {
6720 AllowConstructorName = (D.getContext() == DeclaratorContext::Member);
6721 AllowDeductionGuide = (D.getContext() == DeclaratorContext::File ||
6723 }
6724
6725 bool HadScope = D.getCXXScopeSpec().isValid();
6726 SourceLocation TemplateKWLoc;
6728 /*ObjectType=*/nullptr,
6729 /*ObjectHadErrors=*/false,
6730 /*EnteringContext=*/true,
6731 /*AllowDestructorName=*/true, AllowConstructorName,
6732 AllowDeductionGuide, &TemplateKWLoc,
6733 D.getName()) ||
6734 // Once we're past the identifier, if the scope was bad, mark the
6735 // whole declarator bad.
6736 D.getCXXScopeSpec().isInvalid()) {
6737 D.SetIdentifier(nullptr, Tok.getLocation());
6738 D.setInvalidType(true);
6739 } else {
6740 // ParseUnqualifiedId might have parsed a scope specifier during error
6741 // recovery. If it did so, enter that scope.
6742 if (!HadScope && D.getCXXScopeSpec().isValid() &&
6743 Actions.ShouldEnterDeclaratorScope(getCurScope(),
6744 D.getCXXScopeSpec()))
6745 DeclScopeObj.EnterDeclaratorScope();
6746
6747 // Parsed the unqualified-id; update range information and move along.
6748 if (D.getSourceRange().getBegin().isInvalid())
6751 }
6752 goto PastIdentifier;
6753 }
6754
6755 if (D.getCXXScopeSpec().isNotEmpty()) {
6756 // We have a scope specifier but no following unqualified-id.
6757 Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
6758 diag::err_expected_unqualified_id)
6759 << /*C++*/1;
6760 D.SetIdentifier(nullptr, Tok.getLocation());
6761 goto PastIdentifier;
6762 }
6763 } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
6764 assert(!getLangOpts().CPlusPlus &&
6765 "There's a C++-specific check for tok::identifier above");
6766 assert(Tok.getIdentifierInfo() && "Not an identifier?");
6767 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
6768 D.SetRangeEnd(Tok.getLocation());
6769 ConsumeToken();
6770 goto PastIdentifier;
6771 } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
6772 // We're not allowed an identifier here, but we got one. Try to figure out
6773 // if the user was trying to attach a name to the type, or whether the name
6774 // is some unrelated trailing syntax.
6775 bool DiagnoseIdentifier = false;
6776 if (D.hasGroupingParens())
6777 // An identifier within parens is unlikely to be intended to be anything
6778 // other than a name being "declared".
6779 DiagnoseIdentifier = true;
6781 // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
6782 DiagnoseIdentifier =
6783 NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
6784 else if (D.getContext() == DeclaratorContext::AliasDecl ||
6786 // The most likely error is that the ';' was forgotten.
6787 DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
6790 !isCXX11VirtSpecifier(Tok))
6791 DiagnoseIdentifier = NextToken().isOneOf(
6792 tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
6793 if (DiagnoseIdentifier) {
6794 Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
6795 << FixItHint::CreateRemoval(Tok.getLocation());
6796 D.SetIdentifier(nullptr, Tok.getLocation());
6797 ConsumeToken();
6798 goto PastIdentifier;
6799 }
6800 }
6801
6802 if (Tok.is(tok::l_paren)) {
6803 // If this might be an abstract-declarator followed by a direct-initializer,
6804 // check whether this is a valid declarator chunk. If it can't be, assume
6805 // that it's an initializer instead.
6807 RevertingTentativeParsingAction PA(*this);
6808 if (TryParseDeclarator(true, D.mayHaveIdentifier(), true,
6810 TPResult::False) {
6811 D.SetIdentifier(nullptr, Tok.getLocation());
6812 goto PastIdentifier;
6813 }
6814 }
6815
6816 // direct-declarator: '(' declarator ')'
6817 // direct-declarator: '(' attributes declarator ')'
6818 // Example: 'char (*X)' or 'int (*XX)(void)'
6819 ParseParenDeclarator(D);
6820
6821 // If the declarator was parenthesized, we entered the declarator
6822 // scope when parsing the parenthesized declarator, then exited
6823 // the scope already. Re-enter the scope, if we need to.
6824 if (D.getCXXScopeSpec().isSet()) {
6825 // If there was an error parsing parenthesized declarator, declarator
6826 // scope may have been entered before. Don't do it again.
6827 if (!D.isInvalidType() &&
6828 Actions.ShouldEnterDeclaratorScope(getCurScope(),
6829 D.getCXXScopeSpec()))
6830 // Change the declaration context for name lookup, until this function
6831 // is exited (and the declarator has been parsed).
6832 DeclScopeObj.EnterDeclaratorScope();
6833 }
6834 } else if (D.mayOmitIdentifier()) {
6835 // This could be something simple like "int" (in which case the declarator
6836 // portion is empty), if an abstract-declarator is allowed.
6837 D.SetIdentifier(nullptr, Tok.getLocation());
6838
6839 // The grammar for abstract-pack-declarator does not allow grouping parens.
6840 // FIXME: Revisit this once core issue 1488 is resolved.
6841 if (D.hasEllipsis() && D.hasGroupingParens())
6842 Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
6843 diag::ext_abstract_pack_declarator_parens);
6844 } else {
6845 if (Tok.getKind() == tok::annot_pragma_parser_crash)
6846 LLVM_BUILTIN_TRAP;
6847 if (Tok.is(tok::l_square))
6848 return ParseMisplacedBracketDeclarator(D);
6850 // Objective-C++: Detect C++ keywords and try to prevent further errors by
6851 // treating these keyword as valid member names.
6853 !Tok.isAnnotation() && Tok.getIdentifierInfo() &&
6854 Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
6855 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6856 diag::err_expected_member_name_or_semi_objcxx_keyword)
6857 << Tok.getIdentifierInfo()
6858 << (D.getDeclSpec().isEmpty() ? SourceRange()
6859 : D.getDeclSpec().getSourceRange());
6860 D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
6861 D.SetRangeEnd(Tok.getLocation());
6862 ConsumeToken();
6863 goto PastIdentifier;
6864 }
6865 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6866 diag::err_expected_member_name_or_semi)
6867 << (D.getDeclSpec().isEmpty() ? SourceRange()
6868 : D.getDeclSpec().getSourceRange());
6869 } else {
6870 if (Tok.getKind() == tok::TokenKind::kw_while) {
6871 Diag(Tok, diag::err_while_loop_outside_of_a_function);
6872 } else if (getLangOpts().CPlusPlus) {
6873 if (Tok.isOneOf(tok::period, tok::arrow))
6874 Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
6875 else {
6876 SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
6877 if (Tok.isAtStartOfLine() && Loc.isValid())
6878 Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
6879 << getLangOpts().CPlusPlus;
6880 else
6881 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6882 diag::err_expected_unqualified_id)
6883 << getLangOpts().CPlusPlus;
6884 }
6885 } else {
6886 Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6887 diag::err_expected_either)
6888 << tok::identifier << tok::l_paren;
6889 }
6890 }
6891 D.SetIdentifier(nullptr, Tok.getLocation());
6892 D.setInvalidType(true);
6893 }
6894
6895 PastIdentifier:
6896 assert(D.isPastIdentifier() &&
6897 "Haven't past the location of the identifier yet?");
6898
6899 // Don't parse attributes unless we have parsed an unparenthesized name.
6900 if (D.hasName() && !D.getNumTypeObjects())
6901 MaybeParseCXX11Attributes(D);
6902
6903 while (true) {
6904 if (Tok.is(tok::l_paren)) {
6905 bool IsFunctionDeclaration = D.isFunctionDeclaratorAFunctionDeclaration();
6906 // Enter function-declaration scope, limiting any declarators to the
6907 // function prototype scope, including parameter declarators.
6908 ParseScope PrototypeScope(
6910 (IsFunctionDeclaration ? Scope::FunctionDeclarationScope
6911 : Scope::NoScope));
6912
6913 // The paren may be part of a C++ direct initializer, eg. "int x(1);".
6914 // In such a case, check if we actually have a function declarator; if it
6915 // is not, the declarator has been fully parsed.
6916 bool IsAmbiguous = false;
6918 // C++2a [temp.res]p5
6919 // A qualified-id is assumed to name a type if
6920 // - [...]
6921 // - it is a decl-specifier of the decl-specifier-seq of a
6922 // - [...]
6923 // - parameter-declaration in a member-declaration [...]
6924 // - parameter-declaration in a declarator of a function or function
6925 // template declaration whose declarator-id is qualified [...]
6926 auto AllowImplicitTypename = ImplicitTypenameContext::No;
6927 if (D.getCXXScopeSpec().isSet())
6928 AllowImplicitTypename =
6929 (ImplicitTypenameContext)Actions.isDeclaratorFunctionLike(D);
6930 else if (D.getContext() == DeclaratorContext::Member) {
6931 AllowImplicitTypename = ImplicitTypenameContext::Yes;
6932 }
6933
6934 // The name of the declarator, if any, is tentatively declared within
6935 // a possible direct initializer.
6936 TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
6937 bool IsFunctionDecl =
6938 isCXXFunctionDeclarator(&IsAmbiguous, AllowImplicitTypename);
6939 TentativelyDeclaredIdentifiers.pop_back();
6940 if (!IsFunctionDecl)
6941 break;
6942 }
6943 ParsedAttributes attrs(AttrFactory);
6944 BalancedDelimiterTracker T(*this, tok::l_paren);
6945 T.consumeOpen();
6946 if (IsFunctionDeclaration)
6947 Actions.ActOnStartFunctionDeclarationDeclarator(D,
6948 TemplateParameterDepth);
6949 ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
6950 if (IsFunctionDeclaration)
6951 Actions.ActOnFinishFunctionDeclarationDeclarator(D);
6952 PrototypeScope.Exit();
6953 } else if (Tok.is(tok::l_square)) {
6954 ParseBracketDeclarator(D);
6955 } else if (Tok.isRegularKeywordAttribute()) {
6956 // For consistency with attribute parsing.
6957 Diag(Tok, diag::err_keyword_not_allowed) << Tok.getIdentifierInfo();
6958 bool TakesArgs = doesKeywordAttributeTakeArgs(Tok.getKind());
6959 ConsumeToken();
6960 if (TakesArgs) {
6961 BalancedDelimiterTracker T(*this, tok::l_paren);
6962 if (!T.consumeOpen())
6963 T.skipToEnd();
6964 }
6965 } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
6966 // This declarator is declaring a function, but the requires clause is
6967 // in the wrong place:
6968 // void (f() requires true);
6969 // instead of
6970 // void f() requires true;
6971 // or
6972 // void (f()) requires true;
6973 Diag(Tok, diag::err_requires_clause_inside_parens);
6974 ConsumeToken();
6975 ExprResult TrailingRequiresClause =
6976 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
6977 if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
6979 // We're already ill-formed if we got here but we'll accept it anyway.
6980 D.setTrailingRequiresClause(TrailingRequiresClause.get());
6981 } else {
6982 break;
6983 }
6984 }
6985}
6986
6987void Parser::ParseDecompositionDeclarator(Declarator &D) {
6988 assert(Tok.is(tok::l_square));
6989
6990 TentativeParsingAction PA(*this);
6991 BalancedDelimiterTracker T(*this, tok::l_square);
6992 T.consumeOpen();
6993
6994 if (isCXX11AttributeSpecifier() != CXX11AttributeKind::NotAttributeSpecifier)
6995 DiagnoseAndSkipCXX11Attributes();
6996
6997 // If this doesn't look like a structured binding, maybe it's a misplaced
6998 // array declarator.
6999 if (!(Tok.isOneOf(tok::identifier, tok::ellipsis) &&
7000 NextToken().isOneOf(tok::comma, tok::r_square, tok::kw_alignas,
7001 tok::identifier, tok::l_square, tok::ellipsis)) &&
7002 !(Tok.is(tok::r_square) &&
7003 NextToken().isOneOf(tok::equal, tok::l_brace))) {
7004 PA.Revert();
7005 return ParseMisplacedBracketDeclarator(D);
7006 }
7007
7008 SourceLocation PrevEllipsisLoc;
7009 SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
7010 while (Tok.isNot(tok::r_square)) {
7011 if (!Bindings.empty()) {
7012 if (Tok.is(tok::comma))
7013 ConsumeToken();
7014 else {
7015 if (Tok.is(tok::identifier)) {
7016 SourceLocation EndLoc = getEndOfPreviousToken();
7017 Diag(EndLoc, diag::err_expected)
7018 << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
7019 } else {
7020 Diag(Tok, diag::err_expected_comma_or_rsquare);
7021 }
7022
7023 SkipUntil({tok::r_square, tok::comma, tok::identifier, tok::ellipsis},
7025 if (Tok.is(tok::comma))
7026 ConsumeToken();
7027 else if (Tok.is(tok::r_square))
7028 break;
7029 }
7030 }
7031
7032 if (isCXX11AttributeSpecifier() !=
7034 DiagnoseAndSkipCXX11Attributes();
7035
7036 SourceLocation EllipsisLoc;
7037
7038 if (Tok.is(tok::ellipsis)) {
7039 Diag(Tok, getLangOpts().CPlusPlus26 ? diag::warn_cxx23_compat_binding_pack
7040 : diag::ext_cxx_binding_pack);
7041 if (PrevEllipsisLoc.isValid()) {
7042 Diag(Tok, diag::err_binding_multiple_ellipses);
7043 Diag(PrevEllipsisLoc, diag::note_previous_ellipsis);
7044 break;
7045 }
7046 EllipsisLoc = Tok.getLocation();
7047 PrevEllipsisLoc = EllipsisLoc;
7048 ConsumeToken();
7049 }
7050
7051 if (Tok.isNot(tok::identifier)) {
7052 Diag(Tok, diag::err_expected) << tok::identifier;
7053 break;
7054 }
7055
7056 IdentifierInfo *II = Tok.getIdentifierInfo();
7057 SourceLocation Loc = Tok.getLocation();
7058 ConsumeToken();
7059
7060 if (Tok.is(tok::ellipsis) && !PrevEllipsisLoc.isValid()) {
7061 DiagnoseMisplacedEllipsis(Tok.getLocation(), Loc, EllipsisLoc.isValid(),
7062 true);
7063 EllipsisLoc = Tok.getLocation();
7064 ConsumeToken();
7065 }
7066
7067 ParsedAttributes Attrs(AttrFactory);
7068 if (isCXX11AttributeSpecifier() !=
7071 ? diag::warn_cxx23_compat_decl_attrs_on_binding
7072 : diag::ext_decl_attrs_on_binding);
7073 MaybeParseCXX11Attributes(Attrs);
7074 }
7075
7076 Bindings.push_back({II, Loc, std::move(Attrs), EllipsisLoc});
7077 }
7078
7079 if (Tok.isNot(tok::r_square))
7080 // We've already diagnosed a problem here.
7081 T.skipToEnd();
7082 else {
7083 // C++17 does not allow the identifier-list in a structured binding
7084 // to be empty.
7085 if (Bindings.empty())
7086 Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
7087
7088 T.consumeClose();
7089 }
7090
7091 PA.Commit();
7092
7093 return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
7094 T.getCloseLocation());
7095}
7096
7097void Parser::ParseParenDeclarator(Declarator &D) {
7098 BalancedDelimiterTracker T(*this, tok::l_paren);
7099 T.consumeOpen();
7100
7101 assert(!D.isPastIdentifier() && "Should be called before passing identifier");
7102
7103 // Eat any attributes before we look at whether this is a grouping or function
7104 // declarator paren. If this is a grouping paren, the attribute applies to
7105 // the type being built up, for example:
7106 // int (__attribute__(()) *x)(long y)
7107 // If this ends up not being a grouping paren, the attribute applies to the
7108 // first argument, for example:
7109 // int (__attribute__(()) int x)
7110 // In either case, we need to eat any attributes to be able to determine what
7111 // sort of paren this is.
7112 //
7113 ParsedAttributes attrs(AttrFactory);
7114 bool RequiresArg = false;
7115 if (Tok.is(tok::kw___attribute)) {
7116 ParseGNUAttributes(attrs);
7117
7118 // We require that the argument list (if this is a non-grouping paren) be
7119 // present even if the attribute list was empty.
7120 RequiresArg = true;
7121 }
7122
7123 // Eat any Microsoft extensions.
7124 ParseMicrosoftTypeAttributes(attrs);
7125
7126 // Eat any Borland extensions.
7127 if (Tok.is(tok::kw___pascal))
7128 ParseBorlandTypeAttributes(attrs);
7129
7130 // If we haven't past the identifier yet (or where the identifier would be
7131 // stored, if this is an abstract declarator), then this is probably just
7132 // grouping parens. However, if this could be an abstract-declarator, then
7133 // this could also be the start of function arguments (consider 'void()').
7134 bool isGrouping;
7135
7136 if (!D.mayOmitIdentifier()) {
7137 // If this can't be an abstract-declarator, this *must* be a grouping
7138 // paren, because we haven't seen the identifier yet.
7139 isGrouping = true;
7140 } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
7142 Tok.is(tok::ellipsis) &&
7143 NextToken().is(tok::r_paren)) || // C++ int(...)
7144 isDeclarationSpecifier(
7145 ImplicitTypenameContext::No) || // 'int(int)' is a function.
7146 isCXX11AttributeSpecifier() !=
7148 // is a function.
7149 // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
7150 // considered to be a type, not a K&R identifier-list.
7151 isGrouping = false;
7152 } else {
7153 // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
7154 isGrouping = true;
7155 }
7156
7157 // If this is a grouping paren, handle:
7158 // direct-declarator: '(' declarator ')'
7159 // direct-declarator: '(' attributes declarator ')'
7160 if (isGrouping) {
7161 SourceLocation EllipsisLoc = D.getEllipsisLoc();
7162 D.setEllipsisLoc(SourceLocation());
7163
7164 bool hadGroupingParens = D.hasGroupingParens();
7165 D.setGroupingParens(true);
7166 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
7167 // Match the ')'.
7168 T.consumeClose();
7169 D.AddTypeInfo(
7170 DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
7171 std::move(attrs), T.getCloseLocation());
7172
7173 D.setGroupingParens(hadGroupingParens);
7174
7175 // An ellipsis cannot be placed outside parentheses.
7176 if (EllipsisLoc.isValid())
7177 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
7178
7179 return;
7180 }
7181
7182 // Okay, if this wasn't a grouping paren, it must be the start of a function
7183 // argument list. Recognize that this declarator will never have an
7184 // identifier (and remember where it would have been), then call into
7185 // ParseFunctionDeclarator to handle of argument list.
7186 D.SetIdentifier(nullptr, Tok.getLocation());
7187
7188 // Enter function-declaration scope, limiting any declarators to the
7189 // function prototype scope, including parameter declarators.
7190 ParseScope PrototypeScope(this,
7194 : Scope::NoScope));
7195 ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
7196 PrototypeScope.Exit();
7197}
7198
7199void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
7200 const Declarator &D, const DeclSpec &DS,
7201 std::optional<Sema::CXXThisScopeRAII> &ThisScope) {
7202 // C++11 [expr.prim.general]p3:
7203 // If a declaration declares a member function or member function
7204 // template of a class X, the expression this is a prvalue of type
7205 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
7206 // and the end of the function-definition, member-declarator, or
7207 // declarator.
7208 // FIXME: currently, "static" case isn't handled correctly.
7209 bool IsCXX11MemberFunction =
7210 getLangOpts().CPlusPlus11 &&
7215 D.getCXXScopeSpec().isValid() &&
7216 Actions.CurContext->isRecord());
7217 if (!IsCXX11MemberFunction)
7218 return;
7219
7220 Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
7222 Q.addConst();
7223 // FIXME: Collect C++ address spaces.
7224 // If there are multiple different address spaces, the source is invalid.
7225 // Carry on using the first addr space for the qualifiers of 'this'.
7226 // The diagnostic will be given later while creating the function
7227 // prototype for the method.
7228 if (getLangOpts().OpenCLCPlusPlus) {
7229 for (ParsedAttr &attr : DS.getAttributes()) {
7230 LangAS ASIdx = attr.asOpenCLLangAS();
7231 if (ASIdx != LangAS::Default) {
7232 Q.addAddressSpace(ASIdx);
7233 break;
7234 }
7235 }
7236 }
7237 ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
7238 IsCXX11MemberFunction);
7239}
7240
7241void Parser::ParseFunctionDeclarator(Declarator &D,
7242 ParsedAttributes &FirstArgAttrs,
7243 BalancedDelimiterTracker &Tracker,
7244 bool IsAmbiguous,
7245 bool RequiresArg) {
7246 assert(getCurScope()->isFunctionPrototypeScope() &&
7247 "Should call from a Function scope");
7248 // lparen is already consumed!
7249 assert(D.isPastIdentifier() && "Should not call before identifier!");
7250
7251 // This should be true when the function has typed arguments.
7252 // Otherwise, it is treated as a K&R-style function.
7253 bool HasProto = false;
7254 // Build up an array of information about the parsed arguments.
7255 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
7256 // Remember where we see an ellipsis, if any.
7257 SourceLocation EllipsisLoc;
7258
7259 DeclSpec DS(AttrFactory);
7260 bool RefQualifierIsLValueRef = true;
7261 SourceLocation RefQualifierLoc;
7263 SourceRange ESpecRange;
7264 SmallVector<ParsedType, 2> DynamicExceptions;
7265 SmallVector<SourceRange, 2> DynamicExceptionRanges;
7266 ExprResult NoexceptExpr;
7267 CachedTokens *ExceptionSpecTokens = nullptr;
7268 ParsedAttributes FnAttrs(AttrFactory);
7269 TypeResult TrailingReturnType;
7270 SourceLocation TrailingReturnTypeLoc;
7271
7272 /* LocalEndLoc is the end location for the local FunctionTypeLoc.
7273 EndLoc is the end location for the function declarator.
7274 They differ for trailing return types. */
7275 SourceLocation StartLoc, LocalEndLoc, EndLoc;
7276 SourceLocation LParenLoc, RParenLoc;
7277 LParenLoc = Tracker.getOpenLocation();
7278 StartLoc = LParenLoc;
7279
7280 if (isFunctionDeclaratorIdentifierList()) {
7281 if (RequiresArg)
7282 Diag(Tok, diag::err_argument_required_after_attribute);
7283
7284 ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
7285
7286 Tracker.consumeClose();
7287 RParenLoc = Tracker.getCloseLocation();
7288 LocalEndLoc = RParenLoc;
7289 EndLoc = RParenLoc;
7290
7291 // If there are attributes following the identifier list, parse them and
7292 // prohibit them.
7293 MaybeParseCXX11Attributes(FnAttrs);
7294 ProhibitAttributes(FnAttrs);
7295 } else {
7296 if (Tok.isNot(tok::r_paren))
7297 ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
7298 else if (RequiresArg)
7299 Diag(Tok, diag::err_argument_required_after_attribute);
7300
7301 // OpenCL disallows functions without a prototype, but it doesn't enforce
7302 // strict prototypes as in C23 because it allows a function definition to
7303 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
7304 HasProto = ParamInfo.size() || getLangOpts().requiresStrictPrototypes() ||
7305 getLangOpts().OpenCL;
7306
7307 // If we have the closing ')', eat it.
7308 Tracker.consumeClose();
7309 RParenLoc = Tracker.getCloseLocation();
7310 LocalEndLoc = RParenLoc;
7311 EndLoc = RParenLoc;
7312
7313 if (getLangOpts().CPlusPlus) {
7314 // FIXME: Accept these components in any order, and produce fixits to
7315 // correct the order if the user gets it wrong. Ideally we should deal
7316 // with the pure-specifier in the same way.
7317
7318 // Parse cv-qualifier-seq[opt].
7319 ParseTypeQualifierListOpt(
7320 DS, AR_NoAttributesParsed,
7321 /*AtomicOrPtrauthAllowed=*/false,
7322 /*IdentifierRequired=*/false, [&]() {
7323 Actions.CodeCompletion().CodeCompleteFunctionQualifiers(DS, D);
7324 });
7325 if (!DS.getSourceRange().getEnd().isInvalid()) {
7326 EndLoc = DS.getSourceRange().getEnd();
7327 }
7328
7329 // Parse ref-qualifier[opt].
7330 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
7331 EndLoc = RefQualifierLoc;
7332
7333 std::optional<Sema::CXXThisScopeRAII> ThisScope;
7334 InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
7335
7336 // C++ [class.mem.general]p8:
7337 // A complete-class context of a class (template) is a
7338 // - function body,
7339 // - default argument,
7340 // - default template argument,
7341 // - noexcept-specifier, or
7342 // - default member initializer
7343 // within the member-specification of the class or class template.
7344 //
7345 // Parse exception-specification[opt]. If we are in the
7346 // member-specification of a class or class template, this is a
7347 // complete-class context and parsing of the noexcept-specifier should be
7348 // delayed (even if this is a friend declaration).
7349 bool Delayed = D.getContext() == DeclaratorContext::Member &&
7351 if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
7352 GetLookAheadToken(0).is(tok::kw_noexcept) &&
7353 GetLookAheadToken(1).is(tok::l_paren) &&
7354 GetLookAheadToken(2).is(tok::kw_noexcept) &&
7355 GetLookAheadToken(3).is(tok::l_paren) &&
7356 GetLookAheadToken(4).is(tok::identifier) &&
7357 GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
7358 // HACK: We've got an exception-specification
7359 // noexcept(noexcept(swap(...)))
7360 // or
7361 // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
7362 // on a 'swap' member function. This is a libstdc++ bug; the lookup
7363 // for 'swap' will only find the function we're currently declaring,
7364 // whereas it expects to find a non-member swap through ADL. Turn off
7365 // delayed parsing to give it a chance to find what it expects.
7366 Delayed = false;
7367 }
7368 ESpecType = tryParseExceptionSpecification(Delayed,
7369 ESpecRange,
7370 DynamicExceptions,
7371 DynamicExceptionRanges,
7372 NoexceptExpr,
7373 ExceptionSpecTokens);
7374 if (ESpecType != EST_None)
7375 EndLoc = ESpecRange.getEnd();
7376
7377 // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
7378 // after the exception-specification.
7379 MaybeParseCXX11Attributes(FnAttrs);
7380
7381 // Parse trailing-return-type[opt].
7382 LocalEndLoc = EndLoc;
7383 if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
7384 Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
7386 StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
7387 LocalEndLoc = Tok.getLocation();
7388 SourceRange Range;
7389 TrailingReturnType =
7390 ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
7391 TrailingReturnTypeLoc = Range.getBegin();
7392 EndLoc = Range.getEnd();
7393 }
7394 } else {
7395 MaybeParseCXX11Attributes(FnAttrs);
7396 }
7397 }
7398
7399 // Collect non-parameter declarations from the prototype if this is a function
7400 // declaration. They will be moved into the scope of the function. Only do
7401 // this in C and not C++, where the decls will continue to live in the
7402 // surrounding context.
7403 SmallVector<NamedDecl *, 0> DeclsInPrototype;
7404 if (getCurScope()->isFunctionDeclarationScope() && !getLangOpts().CPlusPlus) {
7405 for (Decl *D : getCurScope()->decls()) {
7406 NamedDecl *ND = dyn_cast<NamedDecl>(D);
7407 if (!ND || isa<ParmVarDecl>(ND))
7408 continue;
7409 DeclsInPrototype.push_back(ND);
7410 }
7411 // Sort DeclsInPrototype based on raw encoding of the source location.
7412 // Scope::decls() is iterating over a SmallPtrSet so sort the Decls before
7413 // moving to DeclContext. This provides a stable ordering for traversing
7414 // Decls in DeclContext, which is important for tasks like ASTWriter for
7415 // deterministic output.
7416 llvm::sort(DeclsInPrototype, [](Decl *D1, Decl *D2) {
7417 return D1->getLocation().getRawEncoding() <
7419 });
7420 }
7421
7422 // Remember that we parsed a function type, and remember the attributes.
7424 HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
7425 ParamInfo.size(), EllipsisLoc, RParenLoc,
7426 RefQualifierIsLValueRef, RefQualifierLoc,
7427 /*MutableLoc=*/SourceLocation(),
7428 ESpecType, ESpecRange, DynamicExceptions.data(),
7429 DynamicExceptionRanges.data(), DynamicExceptions.size(),
7430 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
7431 ExceptionSpecTokens, DeclsInPrototype, StartLoc,
7432 LocalEndLoc, D, TrailingReturnType, TrailingReturnTypeLoc,
7433 &DS),
7434 std::move(FnAttrs), EndLoc);
7435}
7436
7437bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
7438 SourceLocation &RefQualifierLoc) {
7439 if (Tok.isOneOf(tok::amp, tok::ampamp)) {
7441 diag::warn_cxx98_compat_ref_qualifier :
7442 diag::ext_ref_qualifier);
7443
7444 RefQualifierIsLValueRef = Tok.is(tok::amp);
7445 RefQualifierLoc = ConsumeToken();
7446 return true;
7447 }
7448 return false;
7449}
7450
7451bool Parser::isFunctionDeclaratorIdentifierList() {
7453 && Tok.is(tok::identifier)
7454 && !TryAltiVecVectorToken()
7455 // K&R identifier lists can't have typedefs as identifiers, per C99
7456 // 6.7.5.3p11.
7457 && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
7458 // Identifier lists follow a really simple grammar: the identifiers can
7459 // be followed *only* by a ", identifier" or ")". However, K&R
7460 // identifier lists are really rare in the brave new modern world, and
7461 // it is very common for someone to typo a type in a non-K&R style
7462 // list. If we are presented with something like: "void foo(intptr x,
7463 // float y)", we don't want to start parsing the function declarator as
7464 // though it is a K&R style declarator just because intptr is an
7465 // invalid type.
7466 //
7467 // To handle this, we check to see if the token after the first
7468 // identifier is a "," or ")". Only then do we parse it as an
7469 // identifier list.
7470 && (!Tok.is(tok::eof) &&
7471 (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
7472}
7473
7474void Parser::ParseFunctionDeclaratorIdentifierList(
7475 Declarator &D,
7477 // We should never reach this point in C23 or C++.
7478 assert(!getLangOpts().requiresStrictPrototypes() &&
7479 "Cannot parse an identifier list in C23 or C++");
7480
7481 // If there was no identifier specified for the declarator, either we are in
7482 // an abstract-declarator, or we are in a parameter declarator which was found
7483 // to be abstract. In abstract-declarators, identifier lists are not valid:
7484 // diagnose this.
7485 if (!D.getIdentifier())
7486 Diag(Tok, diag::ext_ident_list_in_param);
7487
7488 // Maintain an efficient lookup of params we have seen so far.
7489 llvm::SmallPtrSet<const IdentifierInfo *, 16> ParamsSoFar;
7490
7491 do {
7492 // If this isn't an identifier, report the error and skip until ')'.
7493 if (Tok.isNot(tok::identifier)) {
7494 Diag(Tok, diag::err_expected) << tok::identifier;
7495 SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
7496 // Forget we parsed anything.
7497 ParamInfo.clear();
7498 return;
7499 }
7500
7501 IdentifierInfo *ParmII = Tok.getIdentifierInfo();
7502
7503 // Reject 'typedef int y; int test(x, y)', but continue parsing.
7504 if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
7505 Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
7506
7507 // Verify that the argument identifier has not already been mentioned.
7508 if (!ParamsSoFar.insert(ParmII).second) {
7509 Diag(Tok, diag::err_param_redefinition) << ParmII;
7510 } else {
7511 // Remember this identifier in ParamInfo.
7512 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7513 Tok.getLocation(),
7514 nullptr));
7515 }
7516
7517 // Eat the identifier.
7518 ConsumeToken();
7519 // The list continues if we see a comma.
7520 } while (TryConsumeToken(tok::comma));
7521}
7522
7523void Parser::ParseParameterDeclarationClause(
7524 DeclaratorContext DeclaratorCtx, ParsedAttributes &FirstArgAttrs,
7526 SourceLocation &EllipsisLoc, bool IsACXXFunctionDeclaration) {
7527
7528 // Avoid exceeding the maximum function scope depth.
7529 // See https://bugs.llvm.org/show_bug.cgi?id=19607
7530 // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
7531 // getFunctionPrototypeDepth() - 1.
7532 if (getCurScope()->getFunctionPrototypeDepth() - 1 >
7534 Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
7536 cutOffParsing();
7537 return;
7538 }
7539
7540 // C++2a [temp.res]p5
7541 // A qualified-id is assumed to name a type if
7542 // - [...]
7543 // - it is a decl-specifier of the decl-specifier-seq of a
7544 // - [...]
7545 // - parameter-declaration in a member-declaration [...]
7546 // - parameter-declaration in a declarator of a function or function
7547 // template declaration whose declarator-id is qualified [...]
7548 // - parameter-declaration in a lambda-declarator [...]
7549 auto AllowImplicitTypename = ImplicitTypenameContext::No;
7550 if (DeclaratorCtx == DeclaratorContext::Member ||
7551 DeclaratorCtx == DeclaratorContext::LambdaExpr ||
7552 DeclaratorCtx == DeclaratorContext::RequiresExpr ||
7553 IsACXXFunctionDeclaration) {
7554 AllowImplicitTypename = ImplicitTypenameContext::Yes;
7555 }
7556
7557 do {
7558 // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
7559 // before deciding this was a parameter-declaration-clause.
7560 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
7561 break;
7562
7563 // Parse the declaration-specifiers.
7564 // Just use the ParsingDeclaration "scope" of the declarator.
7565 DeclSpec DS(AttrFactory);
7566
7567 ParsedAttributes ArgDeclAttrs(AttrFactory);
7568 ParsedAttributes ArgDeclSpecAttrs(AttrFactory);
7569
7570 if (FirstArgAttrs.Range.isValid()) {
7571 // If the caller parsed attributes for the first argument, add them now.
7572 // Take them so that we only apply the attributes to the first parameter.
7573 // We have already started parsing the decl-specifier sequence, so don't
7574 // parse any parameter-declaration pieces that precede it.
7575 ArgDeclSpecAttrs.takeAllPrependingFrom(FirstArgAttrs);
7576 } else {
7577 // Parse any C++11 attributes.
7578 MaybeParseCXX11Attributes(ArgDeclAttrs);
7579
7580 // Skip any Microsoft attributes before a param.
7581 MaybeParseMicrosoftAttributes(ArgDeclSpecAttrs);
7582 }
7583
7584 SourceLocation DSStart = Tok.getLocation();
7585
7586 // Parse a C++23 Explicit Object Parameter
7587 // We do that in all language modes to produce a better diagnostic.
7588 SourceLocation ThisLoc;
7589 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_this))
7590 ThisLoc = ConsumeToken();
7591
7592 ParsedTemplateInfo TemplateInfo;
7593 ParseDeclarationSpecifiers(DS, TemplateInfo, AS_none,
7594 DeclSpecContext::DSC_normal,
7595 /*LateAttrs=*/nullptr, AllowImplicitTypename);
7596
7597 DS.takeAttributesAppendingingFrom(ArgDeclSpecAttrs);
7598
7599 // Parse the declarator. This is "PrototypeContext" or
7600 // "LambdaExprParameterContext", because we must accept either
7601 // 'declarator' or 'abstract-declarator' here.
7602 Declarator ParmDeclarator(DS, ArgDeclAttrs,
7603 DeclaratorCtx == DeclaratorContext::RequiresExpr
7605 : DeclaratorCtx == DeclaratorContext::LambdaExpr
7608 ParseDeclarator(ParmDeclarator);
7609
7610 if (ThisLoc.isValid())
7611 ParmDeclarator.SetRangeBegin(ThisLoc);
7612
7613 // Parse GNU attributes, if present.
7614 MaybeParseGNUAttributes(ParmDeclarator);
7615 if (getLangOpts().HLSL)
7616 MaybeParseHLSLAnnotations(DS.getAttributes());
7617
7618 if (Tok.is(tok::kw_requires)) {
7619 // User tried to define a requires clause in a parameter declaration,
7620 // which is surely not a function declaration.
7621 // void f(int (*g)(int, int) requires true);
7622 Diag(Tok,
7623 diag::err_requires_clause_on_declarator_not_declaring_a_function);
7624 ConsumeToken();
7625 ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
7626 }
7627
7628 // Remember this parsed parameter in ParamInfo.
7629 const IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
7630
7631 // DefArgToks is used when the parsing of default arguments needs
7632 // to be delayed.
7633 std::unique_ptr<CachedTokens> DefArgToks;
7634
7635 // If no parameter was specified, verify that *something* was specified,
7636 // otherwise we have a missing type and identifier.
7637 if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
7638 ParmDeclarator.getNumTypeObjects() == 0) {
7639 // Completely missing, emit error.
7640 Diag(DSStart, diag::err_missing_param);
7641 } else {
7642 // Otherwise, we have something. Add it and let semantic analysis try
7643 // to grok it and add the result to the ParamInfo we are building.
7644
7645 // Last chance to recover from a misplaced ellipsis in an attempted
7646 // parameter pack declaration.
7647 if (Tok.is(tok::ellipsis) &&
7648 (NextToken().isNot(tok::r_paren) ||
7649 (!ParmDeclarator.getEllipsisLoc().isValid() &&
7650 !Actions.isUnexpandedParameterPackPermitted())) &&
7651 Actions.containsUnexpandedParameterPacks(ParmDeclarator))
7652 DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
7653
7654 // Now we are at the point where declarator parsing is finished.
7655 //
7656 // Try to catch keywords in place of the identifier in a declarator, and
7657 // in particular the common case where:
7658 // 1 identifier comes at the end of the declarator
7659 // 2 if the identifier is dropped, the declarator is valid but anonymous
7660 // (no identifier)
7661 // 3 declarator parsing succeeds, and then we have a trailing keyword,
7662 // which is never valid in a param list (e.g. missing a ',')
7663 // And we can't handle this in ParseDeclarator because in general keywords
7664 // may be allowed to follow the declarator. (And in some cases there'd be
7665 // better recovery like inserting punctuation). ParseDeclarator is just
7666 // treating this as an anonymous parameter, and fortunately at this point
7667 // we've already almost done that.
7668 //
7669 // We care about case 1) where the declarator type should be known, and
7670 // the identifier should be null.
7671 if (!ParmDeclarator.isInvalidType() && !ParmDeclarator.hasName() &&
7672 Tok.isNot(tok::raw_identifier) && !Tok.isAnnotation() &&
7673 Tok.getIdentifierInfo() &&
7674 Tok.getIdentifierInfo()->isKeyword(getLangOpts())) {
7675 Diag(Tok, diag::err_keyword_as_parameter) << PP.getSpelling(Tok);
7676 // Consume the keyword.
7677 ConsumeToken();
7678 }
7679
7680 // We can only store so many parameters
7681 // Skip until the the end of the parameter list, ignoring
7682 // parameters that would overflow.
7683 if (ParamInfo.size() == Type::FunctionTypeNumParamsLimit) {
7684 Diag(ParmDeclarator.getBeginLoc(),
7685 diag::err_function_parameter_limit_exceeded);
7687 break;
7688 }
7689
7690 // Inform the actions module about the parameter declarator, so it gets
7691 // added to the current scope.
7692 Decl *Param =
7693 Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator, ThisLoc);
7694 // Parse the default argument, if any. We parse the default
7695 // arguments in all dialects; the semantic analysis in
7696 // ActOnParamDefaultArgument will reject the default argument in
7697 // C.
7698 if (Tok.is(tok::equal)) {
7699 SourceLocation EqualLoc = Tok.getLocation();
7700
7701 // Parse the default argument
7702 if (DeclaratorCtx == DeclaratorContext::Member) {
7703 // If we're inside a class definition, cache the tokens
7704 // corresponding to the default argument. We'll actually parse
7705 // them when we see the end of the class definition.
7706 DefArgToks.reset(new CachedTokens);
7707
7708 SourceLocation ArgStartLoc = NextToken().getLocation();
7709 ConsumeAndStoreInitializer(*DefArgToks,
7711 Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
7712 ArgStartLoc);
7713 } else {
7714 // Consume the '='.
7715 ConsumeToken();
7716
7717 // The argument isn't actually potentially evaluated unless it is
7718 // used.
7719 EnterExpressionEvaluationContext Eval(
7720 Actions,
7722 Param);
7723
7724 ExprResult DefArgResult;
7725 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
7726 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
7727 DefArgResult = ParseBraceInitializer();
7728 } else {
7729 if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
7730 Diag(Tok, diag::err_stmt_expr_in_default_arg) << 0;
7731 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
7732 /*DefaultArg=*/nullptr);
7733 // Skip the statement expression and continue parsing
7734 SkipUntil(tok::comma, StopBeforeMatch);
7735 continue;
7736 }
7737 DefArgResult = ParseAssignmentExpression();
7738 }
7739 if (DefArgResult.isInvalid()) {
7740 Actions.ActOnParamDefaultArgumentError(Param, EqualLoc,
7741 /*DefaultArg=*/nullptr);
7742 SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
7743 } else {
7744 // Inform the actions module about the default argument
7745 Actions.ActOnParamDefaultArgument(Param, EqualLoc,
7746 DefArgResult.get());
7747 }
7748 }
7749 }
7750
7751 ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
7752 ParmDeclarator.getIdentifierLoc(),
7753 Param, std::move(DefArgToks)));
7754 }
7755
7756 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
7757 if (getLangOpts().CPlusPlus26) {
7758 // C++26 [dcl.dcl.fct]p3:
7759 // A parameter-declaration-clause of the form
7760 // parameter-list '...' is deprecated.
7761 Diag(EllipsisLoc, diag::warn_deprecated_missing_comma_before_ellipsis)
7762 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7763 }
7764
7765 if (!getLangOpts().CPlusPlus) {
7766 // We have ellipsis without a preceding ',', which is ill-formed
7767 // in C. Complain and provide the fix.
7768 Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
7769 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7770 } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
7771 Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
7772 // It looks like this was supposed to be a parameter pack. Warn and
7773 // point out where the ellipsis should have gone.
7774 SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
7775 Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
7776 << ParmEllipsis.isValid() << ParmEllipsis;
7777 if (ParmEllipsis.isValid()) {
7778 Diag(ParmEllipsis,
7779 diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
7780 } else {
7781 Diag(ParmDeclarator.getIdentifierLoc(),
7782 diag::note_misplaced_ellipsis_vararg_add_ellipsis)
7783 << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
7784 "...")
7785 << !ParmDeclarator.hasName();
7786 }
7787 Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
7788 << FixItHint::CreateInsertion(EllipsisLoc, ", ");
7789 }
7790
7791 // We can't have any more parameters after an ellipsis.
7792 break;
7793 }
7794
7795 // If the next token is a comma, consume it and keep reading arguments.
7796 } while (TryConsumeToken(tok::comma));
7797}
7798
7799void Parser::ParseBracketDeclarator(Declarator &D) {
7800 if (CheckProhibitedCXX11Attribute())
7801 return;
7802
7803 BalancedDelimiterTracker T(*this, tok::l_square);
7804 T.consumeOpen();
7805
7806 // C array syntax has many features, but by-far the most common is [] and [4].
7807 // This code does a fast path to handle some of the most obvious cases.
7808 if (Tok.getKind() == tok::r_square) {
7809 T.consumeClose();
7810 ParsedAttributes attrs(AttrFactory);
7811 MaybeParseCXX11Attributes(attrs);
7812
7813 // Remember that we parsed the empty array type.
7814 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
7815 T.getOpenLocation(),
7816 T.getCloseLocation()),
7817 std::move(attrs), T.getCloseLocation());
7818 return;
7819 } else if (Tok.getKind() == tok::numeric_constant &&
7820 GetLookAheadToken(1).is(tok::r_square)) {
7821 // [4] is very common. Parse the numeric constant expression.
7822 ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
7823 ConsumeToken();
7824
7825 T.consumeClose();
7826 ParsedAttributes attrs(AttrFactory);
7827 MaybeParseCXX11Attributes(attrs);
7828
7829 // Remember that we parsed a array type, and remember its features.
7830 D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
7831 T.getOpenLocation(),
7832 T.getCloseLocation()),
7833 std::move(attrs), T.getCloseLocation());
7834 return;
7835 } else if (Tok.getKind() == tok::code_completion) {
7836 cutOffParsing();
7837 Actions.CodeCompletion().CodeCompleteBracketDeclarator(getCurScope());
7838 return;
7839 }
7840
7841 // If valid, this location is the position where we read the 'static' keyword.
7842 SourceLocation StaticLoc;
7843 TryConsumeToken(tok::kw_static, StaticLoc);
7844
7845 // If there is a type-qualifier-list, read it now.
7846 // Type qualifiers in an array subscript are a C99 feature.
7847 DeclSpec DS(AttrFactory);
7848 ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
7849
7850 // If we haven't already read 'static', check to see if there is one after the
7851 // type-qualifier-list.
7852 if (!StaticLoc.isValid())
7853 TryConsumeToken(tok::kw_static, StaticLoc);
7854
7855 // Handle "direct-declarator [ type-qual-list[opt] * ]".
7856 bool isStar = false;
7857 ExprResult NumElements;
7858
7859 // Handle the case where we have '[*]' as the array size. However, a leading
7860 // star could be the start of an expression, for example 'X[*p + 4]'. Verify
7861 // the token after the star is a ']'. Since stars in arrays are
7862 // infrequent, use of lookahead is not costly here.
7863 if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
7864 ConsumeToken(); // Eat the '*'.
7865
7866 if (StaticLoc.isValid()) {
7867 Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
7868 StaticLoc = SourceLocation(); // Drop the static.
7869 }
7870 isStar = true;
7871 } else if (Tok.isNot(tok::r_square)) {
7872 // Note, in C89, this production uses the constant-expr production instead
7873 // of assignment-expr. The only difference is that assignment-expr allows
7874 // things like '=' and '*='. Sema rejects these in C89 mode because they
7875 // are not i-c-e's, so we don't need to distinguish between the two here.
7876
7877 // Parse the constant-expression or assignment-expression now (depending
7878 // on dialect).
7879 if (getLangOpts().CPlusPlus) {
7880 NumElements = ParseArrayBoundExpression();
7881 } else {
7882 EnterExpressionEvaluationContext Unevaluated(
7884 NumElements = ParseAssignmentExpression();
7885 }
7886 } else {
7887 if (StaticLoc.isValid()) {
7888 Diag(StaticLoc, diag::err_unspecified_size_with_static);
7889 StaticLoc = SourceLocation(); // Drop the static.
7890 }
7891 }
7892
7893 // If there was an error parsing the assignment-expression, recover.
7894 if (NumElements.isInvalid()) {
7895 D.setInvalidType(true);
7896 // If the expression was invalid, skip it.
7897 SkipUntil(tok::r_square, StopAtSemi);
7898 return;
7899 }
7900
7901 T.consumeClose();
7902
7903 MaybeParseCXX11Attributes(DS.getAttributes());
7904
7905 // Remember that we parsed a array type, and remember its features.
7906 D.AddTypeInfo(
7908 isStar, NumElements.get(), T.getOpenLocation(),
7909 T.getCloseLocation()),
7910 std::move(DS.getAttributes()), T.getCloseLocation());
7911}
7912
7913void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
7914 assert(Tok.is(tok::l_square) && "Missing opening bracket");
7915 assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
7916
7917 SourceLocation StartBracketLoc = Tok.getLocation();
7919 D.getContext());
7920
7921 while (Tok.is(tok::l_square)) {
7922 ParseBracketDeclarator(TempDeclarator);
7923 }
7924
7925 // Stuff the location of the start of the brackets into the Declarator.
7926 // The diagnostics from ParseDirectDeclarator will make more sense if
7927 // they use this location instead.
7928 if (Tok.is(tok::semi))
7929 D.getName().EndLocation = StartBracketLoc;
7930
7931 SourceLocation SuggestParenLoc = Tok.getLocation();
7932
7933 // Now that the brackets are removed, try parsing the declarator again.
7934 ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
7935
7936 // Something went wrong parsing the brackets, in which case,
7937 // ParseBracketDeclarator has emitted an error, and we don't need to emit
7938 // one here.
7939 if (TempDeclarator.getNumTypeObjects() == 0)
7940 return;
7941
7942 // Determine if parens will need to be suggested in the diagnostic.
7943 bool NeedParens = false;
7944 if (D.getNumTypeObjects() != 0) {
7945 switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
7951 NeedParens = true;
7952 break;
7956 break;
7957 }
7958 }
7959
7960 if (NeedParens) {
7961 // Create a DeclaratorChunk for the inserted parens.
7962 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7963 D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
7964 SourceLocation());
7965 }
7966
7967 // Adding back the bracket info to the end of the Declarator.
7968 for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
7969 const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
7970 D.AddTypeInfo(Chunk, TempDeclarator.getAttributePool(), SourceLocation());
7971 }
7972
7973 // The missing name would have been diagnosed in ParseDirectDeclarator.
7974 // If parentheses are required, always suggest them.
7975 if (!D.hasName() && !NeedParens)
7976 return;
7977
7978 SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
7979
7980 // Generate the move bracket error message.
7981 SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
7982 SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
7983
7984 if (NeedParens) {
7985 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7986 << getLangOpts().CPlusPlus
7987 << FixItHint::CreateInsertion(SuggestParenLoc, "(")
7988 << FixItHint::CreateInsertion(EndLoc, ")")
7990 EndLoc, CharSourceRange(BracketRange, true))
7991 << FixItHint::CreateRemoval(BracketRange);
7992 } else {
7993 Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
7994 << getLangOpts().CPlusPlus
7996 EndLoc, CharSourceRange(BracketRange, true))
7997 << FixItHint::CreateRemoval(BracketRange);
7998 }
7999}
8000
8001void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
8002 assert(Tok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
8003 "Not a typeof specifier");
8004
8005 bool IsUnqual = Tok.is(tok::kw_typeof_unqual);
8006 const IdentifierInfo *II = Tok.getIdentifierInfo();
8007 if (getLangOpts().C23 && !II->getName().starts_with("__"))
8008 Diag(Tok.getLocation(), diag::warn_c23_compat_keyword) << Tok.getName();
8009
8010 Token OpTok = Tok;
8011 SourceLocation StartLoc = ConsumeToken();
8012 bool HasParens = Tok.is(tok::l_paren);
8013
8014 EnterExpressionEvaluationContext Unevaluated(
8017
8018 bool isCastExpr;
8019 ParsedType CastTy;
8020 SourceRange CastRange;
8022 ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange);
8023 if (HasParens)
8024 DS.setTypeArgumentRange(CastRange);
8025
8026 if (CastRange.getEnd().isInvalid())
8027 // FIXME: Not accurate, the range gets one token more than it should.
8028 DS.SetRangeEnd(Tok.getLocation());
8029 else
8030 DS.SetRangeEnd(CastRange.getEnd());
8031
8032 if (isCastExpr) {
8033 if (!CastTy) {
8034 DS.SetTypeSpecError();
8035 return;
8036 }
8037
8038 const char *PrevSpec = nullptr;
8039 unsigned DiagID;
8040 // Check for duplicate type specifiers (e.g. "int typeof(int)").
8043 StartLoc, PrevSpec,
8044 DiagID, CastTy,
8045 Actions.getASTContext().getPrintingPolicy()))
8046 Diag(StartLoc, DiagID) << PrevSpec;
8047 return;
8048 }
8049
8050 // If we get here, the operand to the typeof was an expression.
8051 if (Operand.isInvalid()) {
8052 DS.SetTypeSpecError();
8053 return;
8054 }
8055
8056 // We might need to transform the operand if it is potentially evaluated.
8057 Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
8058 if (Operand.isInvalid()) {
8059 DS.SetTypeSpecError();
8060 return;
8061 }
8062
8063 const char *PrevSpec = nullptr;
8064 unsigned DiagID;
8065 // Check for duplicate type specifiers (e.g. "int typeof(int)").
8068 StartLoc, PrevSpec,
8069 DiagID, Operand.get(),
8070 Actions.getASTContext().getPrintingPolicy()))
8071 Diag(StartLoc, DiagID) << PrevSpec;
8072}
8073
8074void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
8075 assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
8076 "Not an atomic specifier");
8077
8078 SourceLocation StartLoc = ConsumeToken();
8079 BalancedDelimiterTracker T(*this, tok::l_paren);
8080 if (T.consumeOpen())
8081 return;
8082
8084 if (Result.isInvalid()) {
8085 SkipUntil(tok::r_paren, StopAtSemi);
8086 return;
8087 }
8088
8089 // Match the ')'
8090 T.consumeClose();
8091
8092 if (T.getCloseLocation().isInvalid())
8093 return;
8094
8095 DS.setTypeArgumentRange(T.getRange());
8096 DS.SetRangeEnd(T.getCloseLocation());
8097
8098 const char *PrevSpec = nullptr;
8099 unsigned DiagID;
8100 if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
8101 DiagID, Result.get(),
8102 Actions.getASTContext().getPrintingPolicy()))
8103 Diag(StartLoc, DiagID) << PrevSpec;
8104}
8105
8106bool Parser::TryAltiVecVectorTokenOutOfLine() {
8107 Token Next = NextToken();
8108 switch (Next.getKind()) {
8109 default: return false;
8110 case tok::kw_short:
8111 case tok::kw_long:
8112 case tok::kw_signed:
8113 case tok::kw_unsigned:
8114 case tok::kw_void:
8115 case tok::kw_char:
8116 case tok::kw_int:
8117 case tok::kw_float:
8118 case tok::kw_double:
8119 case tok::kw_bool:
8120 case tok::kw__Bool:
8121 case tok::kw___bool:
8122 case tok::kw___pixel:
8123 Tok.setKind(tok::kw___vector);
8124 return true;
8125 case tok::identifier:
8126 if (Next.getIdentifierInfo() == Ident_pixel) {
8127 Tok.setKind(tok::kw___vector);
8128 return true;
8129 }
8130 if (Next.getIdentifierInfo() == Ident_bool ||
8131 Next.getIdentifierInfo() == Ident_Bool) {
8132 Tok.setKind(tok::kw___vector);
8133 return true;
8134 }
8135 return false;
8136 }
8137}
8138
8139bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
8140 const char *&PrevSpec, unsigned &DiagID,
8141 bool &isInvalid) {
8142 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
8143 if (Tok.getIdentifierInfo() == Ident_vector) {
8144 Token Next = NextToken();
8145 switch (Next.getKind()) {
8146 case tok::kw_short:
8147 case tok::kw_long:
8148 case tok::kw_signed:
8149 case tok::kw_unsigned:
8150 case tok::kw_void:
8151 case tok::kw_char:
8152 case tok::kw_int:
8153 case tok::kw_float:
8154 case tok::kw_double:
8155 case tok::kw_bool:
8156 case tok::kw__Bool:
8157 case tok::kw___bool:
8158 case tok::kw___pixel:
8159 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
8160 return true;
8161 case tok::identifier:
8162 if (Next.getIdentifierInfo() == Ident_pixel) {
8163 isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
8164 return true;
8165 }
8166 if (Next.getIdentifierInfo() == Ident_bool ||
8167 Next.getIdentifierInfo() == Ident_Bool) {
8168 isInvalid =
8169 DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
8170 return true;
8171 }
8172 break;
8173 default:
8174 break;
8175 }
8176 } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
8177 DS.isTypeAltiVecVector()) {
8178 isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
8179 return true;
8180 } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
8181 DS.isTypeAltiVecVector()) {
8182 isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
8183 return true;
8184 }
8185 return false;
8186}
8187
8188TypeResult Parser::ParseTypeFromString(StringRef TypeStr, StringRef Context,
8189 SourceLocation IncludeLoc) {
8190 // Consume (unexpanded) tokens up to the end-of-directive.
8191 SmallVector<Token, 4> Tokens;
8192 {
8193 // Create a new buffer from which we will parse the type.
8194 auto &SourceMgr = PP.getSourceManager();
8195 FileID FID = SourceMgr.createFileID(
8196 llvm::MemoryBuffer::getMemBufferCopy(TypeStr, Context), SrcMgr::C_User,
8197 0, 0, IncludeLoc);
8198
8199 // Form a new lexer that references the buffer.
8200 Lexer L(FID, SourceMgr.getBufferOrFake(FID), PP);
8201 L.setParsingPreprocessorDirective(true);
8202
8203 // Lex the tokens from that buffer.
8204 Token Tok;
8205 do {
8206 L.Lex(Tok);
8207 Tokens.push_back(Tok);
8208 } while (Tok.isNot(tok::eod));
8209 }
8210
8211 // Replace the "eod" token with an "eof" token identifying the end of
8212 // the provided string.
8213 Token &EndToken = Tokens.back();
8214 EndToken.startToken();
8215 EndToken.setKind(tok::eof);
8216 EndToken.setLocation(Tok.getLocation());
8217 EndToken.setEofData(TypeStr.data());
8218
8219 // Add the current token back.
8220 Tokens.push_back(Tok);
8221
8222 // Enter the tokens into the token stream.
8223 PP.EnterTokenStream(Tokens, /*DisableMacroExpansion=*/false,
8224 /*IsReinject=*/false);
8225
8226 // Consume the current token so that we'll start parsing the tokens we
8227 // added to the stream.
8229
8230 // Enter a new scope.
8231 ParseScope LocalScope(this, 0);
8232
8233 // Parse the type.
8234 TypeResult Result = ParseTypeName(nullptr);
8235
8236 // Check if we parsed the whole thing.
8237 if (Result.isUsable() &&
8238 (Tok.isNot(tok::eof) || Tok.getEofData() != TypeStr.data())) {
8239 Diag(Tok.getLocation(), diag::err_type_unparsed);
8240 }
8241
8242 // There could be leftover tokens (e.g. because of an error).
8243 // Skip through until we reach the 'end of directive' token.
8244 while (Tok.isNot(tok::eof))
8246
8247 // Consume the end token.
8248 if (Tok.is(tok::eof) && Tok.getEofData() == TypeStr.data())
8250 return Result;
8251}
8252
8253void Parser::DiagnoseBitIntUse(const Token &Tok) {
8254 // If the token is for _ExtInt, diagnose it as being deprecated. Otherwise,
8255 // the token is about _BitInt and gets (potentially) diagnosed as use of an
8256 // extension.
8257 assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
8258 "expected either an _ExtInt or _BitInt token!");
8259
8260 SourceLocation Loc = Tok.getLocation();
8261 if (Tok.is(tok::kw__ExtInt)) {
8262 Diag(Loc, diag::warn_ext_int_deprecated)
8263 << FixItHint::CreateReplacement(Loc, "_BitInt");
8264 } else {
8265 // In C23 mode, diagnose that the use is not compatible with pre-C23 modes.
8266 // Otherwise, diagnose that the use is a Clang extension.
8267 if (getLangOpts().C23)
8268 Diag(Loc, diag::warn_c23_compat_keyword) << Tok.getName();
8269 else
8270 Diag(Loc, diag::ext_bit_int) << getLangOpts().CPlusPlus;
8271 }
8272}
Defines the clang::ASTContext interface.
Provides definitions for the various language-specific address spaces.
static StringRef normalizeAttrName(StringRef AttrName, StringRef NormalizedScopeName, AttributeCommonInfo::Syntax SyntaxUsed)
static Decl::Kind getKind(const Decl *D)
Defines the C++ template declaration subclasses.
bool is(tok::TokenKind Kind) const
Token Tok
The Token.
bool isNot(T Kind) const
FormatToken * Next
The next token in the unwrapped line.
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::RecordLoc RecordLoc
Definition MachO.h:41
static StringRef getTriple(const Command &Job)
#define SM(sm)
static bool IsAttributeLateParsedExperimentalExt(const IdentifierInfo &II)
returns true iff attribute is annotated with LateAttrParseExperimentalExt in Attr....
Definition ParseDecl.cpp: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:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:181
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:186
SourceLocation getEndLoc() const
Definition DeclSpec.h:85
bool isSet() const
Deprecated.
Definition DeclSpec.h:199
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:184
void setTemplateParamLists(ArrayRef< TemplateParameterList * > L)
Definition DeclSpec.h:87
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:179
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:3486
Captures information about "declaration specifiers".
Definition DeclSpec.h:218
bool isVirtualSpecified() const
Definition DeclSpec.h:653
bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, ExplicitSpecifier ExplicitSpec, SourceLocation CloseParenLoc)
bool isTypeSpecPipe() const
Definition DeclSpec.h:526
void ClearTypeSpecType()
Definition DeclSpec.h:506
static const TSCS TSCS___thread
Definition DeclSpec.h:237
static const TST TST_typeof_unqualType
Definition DeclSpec.h:280
void setTypeArgumentRange(SourceRange range)
Definition DeclSpec.h:576
bool SetTypePipe(bool isPipe, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:898
SourceLocation getPipeLoc() const
Definition DeclSpec.h:606
static const TST TST_typename
Definition DeclSpec.h:277
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:559
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:696
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:631
static const TST TST_char8
Definition DeclSpec.h:253
static const TST TST_BFloat16
Definition DeclSpec.h:260
void ClearStorageClassSpecs()
Definition DeclSpec.h:498
bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
static const TSCS TSCS__Thread_local
Definition DeclSpec.h:239
bool SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec, but return true and ignore the request if ...
Definition DeclSpec.cpp:707
bool isNoreturnSpecified() const
Definition DeclSpec.h:666
TST getTypeSpecType() const
Definition DeclSpec.h:520
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:493
SCS getStorageClassSpec() const
Definition DeclSpec.h:484
bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
SourceLocation getOverflowBehaviorLoc() const
Definition DeclSpec.h:622
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:846
bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition DeclSpec.cpp:870
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:557
bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition DeclSpec.cpp:693
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:714
bool SetBitIntType(SourceLocation KWLoc, Expr *BitWidth, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:957
static const TST TST_auto_type
Definition DeclSpec.h:290
static const TST TST_interface
Definition DeclSpec.h:275
static const TST TST_double
Definition DeclSpec.h:262
static const TST TST_typeofExpr
Definition DeclSpec.h:279
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:600
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:713
bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:915
bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:667
static const TST TST_union
Definition DeclSpec.h:273
static const TST TST_char
Definition DeclSpec.h:251
static const TST TST_bool
Definition DeclSpec.h:268
static const TST TST_char16
Definition DeclSpec.h:254
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:659
SourceLocation getFriendSpecLoc() const
Definition DeclSpec.h:832
static const TST TST_int
Definition DeclSpec.h:256
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:835
bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition DeclSpec.cpp:724
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:793
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:485
bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
bool hasAttributes() const
Definition DeclSpec.h:876
static const TST TST_accum
Definition DeclSpec.h:264
static const TST TST_half
Definition DeclSpec.h:259
ParsedAttributes & getAttributes()
Definition DeclSpec.h:878
bool SetOverflowBehavior(OverflowBehaviorType::OverflowBehaviorKind Kind, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:601
static const TST TST_ibm128
Definition DeclSpec.h:267
void addAttributes(const ParsedAttributesView &AL)
Concatenates two attribute lists.
Definition DeclSpec.h:872
static const TST TST_enum
Definition DeclSpec.h:272
bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:932
bool isWrapSpecified() const
Definition DeclSpec.h:613
static const TST TST_float128
Definition DeclSpec.h:266
void takeAttributesAppendingingFrom(ParsedAttributes &attrs)
Definition DeclSpec.h:881
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:642
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:602
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:281
static const TST TST_class
Definition DeclSpec.h:276
TypeSpecifierType TST
Definition DeclSpec.h:248
bool hasTagDefinition() const
Definition DeclSpec.cpp:433
static const TST TST_decimal64
Definition DeclSpec.h:270
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition DeclSpec.cpp:442
void ClearFunctionSpecs()
Definition DeclSpec.h:669
bool SetTypeQual(TQ T, SourceLocation Loc)
static const TST TST_wchar
Definition DeclSpec.h:252
static const TST TST_void
Definition DeclSpec.h:250
bool isTypeAltiVecVector() const
Definition DeclSpec.h:521
void ClearConstexprSpec()
Definition DeclSpec.h:846
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:261
static const TST TST_atomic
Definition DeclSpec.h:292
static const TST TST_fract
Definition DeclSpec.h:265
bool SetTypeSpecError()
Definition DeclSpec.cpp:949
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:494
Decl * getRepAsDecl() const
Definition DeclSpec.h:534
static const TST TST_float16
Definition DeclSpec.h:263
static const TST TST_unspecified
Definition DeclSpec.h:249
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:604
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:654
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:841
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:554
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
Definition DeclSpec.h:709
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:565
static const TSCS TSCS_thread_local
Definition DeclSpec.h:238
bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
static const TST TST_decimal32
Definition DeclSpec.h:269
bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:883
TypeSpecifierWidth getTypeSpecWidth() const
Definition DeclSpec.h:513
static const TST TST_char32
Definition DeclSpec.h:255
bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
static const TST TST_decimal128
Definition DeclSpec.h:271
bool isTypeSpecOwned() const
Definition DeclSpec.h:524
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:645
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:605
static const TST TST_int128
Definition DeclSpec.h:257
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:603
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:826
bool hasExplicitSpecifier() const
Definition DeclSpec.h:656
bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
bool hasConstexprSpecifier() const
Definition DeclSpec.h:842
static const TST TST_typeofType
Definition DeclSpec.h:278
bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition DeclSpec.cpp:734
static const TST TST_auto
Definition DeclSpec.h:289
@ PQ_StorageClassSpecifier
Definition DeclSpec.h:317
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:837
static const TST TST_struct
Definition DeclSpec.h:274
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1921
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2477
bool isPastIdentifier() const
isPastIdentifier - Return true if we have parsed beyond the point where the name would appear.
Definition DeclSpec.h:2335
void SetRangeBegin(SourceLocation Loc)
SetRangeBegin - Set the start of the source range to Loc, unless it's invalid.
Definition DeclSpec.h:2110
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2419
void setCommaLoc(SourceLocation CL)
Definition DeclSpec.h:2744
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2068
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2357
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2360
bool mayOmitIdentifier() const
mayOmitIdentifier - Return true if the identifier is either optional or not allowed.
Definition DeclSpec.h:2154
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2105
bool mayBeFollowedByCXXDirectInit() const
mayBeFollowedByCXXDirectInit - Return true if the declarator can be followed by a C++ direct initiali...
Definition DeclSpec.h:2277
bool hasGroupingParens() const
Definition DeclSpec.h:2740
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:2734
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2415
bool mayHaveIdentifier() const
mayHaveIdentifier - Return true if the identifier is either optional or required.
Definition DeclSpec.h:2194
void setGroupingParens(bool flag)
Definition DeclSpec.h:2739
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2747
DeclaratorContext getContext() const
Definition DeclSpec.h:2093
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2104
void setTrailingRequiresClause(Expr *TRC)
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2647
void setHasInitializer(bool Val=true)
Definition DeclSpec.h:2766
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2087
void setTemplateParameterLists(ArrayRef< TemplateParameterList * > TPLs)
Sets the template parameter lists that preceded the declarator.
Definition DeclSpec.h:2665
bool isFirstDeclarator() const
Definition DeclSpec.h:2742
bool hasTrailingRequiresClause() const
Determine whether a trailing requires clause was written in this declarator.
Definition DeclSpec.h:2660
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2083
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition DeclSpec.h:2341
ArrayRef< TemplateParameterList * > getTemplateParameterLists() const
The template parameter lists that preceded the declarator.
Definition DeclSpec.h:2670
bool isFunctionDeclaratorAFunctionDeclaration() const
Return true if a function declarator at this position would be a function declaration.
Definition DeclSpec.h:2616
bool hasEllipsis() const
Definition DeclSpec.h:2746
void clear()
Reset the contents of this Declarator.
Definition DeclSpec.h:2131
void setAsmLabel(Expr *E)
Definition DeclSpec.h:2722
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2374
void ExtendWithDeclSpec(const DeclSpec &DS)
ExtendWithDeclSpec - Extend the declarator source range to include the given declspec,...
Definition DeclSpec.h:2122
void SetRangeEnd(SourceLocation Loc)
SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
Definition DeclSpec.h:2115
void setExtension(bool Val=true)
Definition DeclSpec.h:2725
bool isInvalidType() const
Definition DeclSpec.h:2735
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2103
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2508
void setEllipsisLoc(SourceLocation EL)
Definition DeclSpec.h:2748
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2351
Represents an enum.
Definition Decl.h:4028
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
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:117
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
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:975
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:1052
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:889
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:911
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:1353
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:520
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
PtrTy get() const
Definition Ownership.h:81
static constexpr unsigned getMaxFunctionScopeDepth()
Definition Decl.h:1860
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:408
Parser - This implements a parser for the C family of languages.
Definition Parser.h:172
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeName, AccessSpecifier AS=AS_none, Decl **OwnedType=nullptr, ParsedAttributes *Attrs=nullptr)
ParseTypeName.
Definition ParseDecl.cpp:44
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, bool IsAddressOfOperand=false)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition Parser.cpp:1860
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition Parser.cpp:88
SourceLocation getEndOfPreviousToken() const
Definition Parser.cpp:1844
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:263
Sema & getActions() const
Definition Parser.h:208
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition Parser.h:328
void EnterScope(unsigned ScopeFlags)
EnterScope - Start a new scope.
Definition Parser.cpp:428
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:7242
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:197
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:291
const Token & GetLookAheadToken(unsigned N)
GetLookAheadToken - This peeks ahead N tokens and returns that token without consuming any tokens.
Definition Parser.h:317
ExprResult ParseConstantExpression()
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:271
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:220
Scope * getCurScope() const
Definition Parser.h:212
ExprResult ParseArrayBoundExpression()
const TargetInfo & getTargetInfo() const
Definition Parser.h:206
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:507
void SkipMalformedDecl()
SkipMalformedDecl - Read tokens until we get to some likely good stopping point for skipping past a s...
const Token & getCurToken() const
Definition Parser.h:211
void ExitScope()
ExitScope - Pop a scope off the scope stack.
Definition Parser.cpp:438
const LangOptions & getLangOpts() const
Definition Parser.h:205
friend class ParenBraceBracketBalancer
Definition Parser.h:199
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:488
@ StopAtCodeCompletion
Stop at code completion.
Definition Parser.h:489
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:486
ExprResult ParseUnevaluatedStringLiteralExpression()
ObjCContainerDecl * getObjCDeclContext() const
Definition Parser.h:5376
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:325
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:200
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition Parser.h:7834
bool TryAnnotateCXXScopeToken(bool EnteringContext=false)
TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only annotates C++ scope specifiers and ...
Definition Parser.cpp:2105
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:4342
field_range fields() const
Definition Decl.h:4545
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:132
ParserCompletionContext
Describes the context in which code completion occurs.
@ PCC_LocalDeclarationSpecifiers
Code completion occurs within a sequence of declaration specifiers within a function,...
@ PCC_MemberTemplate
Code completion occurs following one or more template headers within a class.
@ PCC_Class
Code completion occurs within a class, struct, or union.
@ PCC_ObjCImplementation
Code completion occurs within an Objective-C implementation or category implementation.
@ PCC_Namespace
Code completion occurs at top-level or namespace context.
@ PCC_Template
Code completion occurs following one or more template headers.
NameClassificationKind getKind() const
Definition Sema.h:3780
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ ReuseLambdaContextDecl
Definition Sema.h:7100
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6810
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6820
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6789
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6830
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:3732
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:197
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
void setKind(tok::TokenKind K)
Definition Token.h:100
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:104
void * getAnnotationValue() const
Definition Token.h:244
tok::TokenKind getKind() const
Definition Token.h:99
bool isOneOf(Ts... Ks) const
Definition Token.h:105
void setEofData(const void *D)
Definition Token.h:214
void setLocation(SourceLocation L)
Definition Token.h:150
void startToken()
Reset all flags to cleared.
Definition Token.h:187
void setSemiMissing(bool Missing=true)
Definition Decl.h:4673
static constexpr int FunctionTypeNumParamsLimit
Definition TypeBase.h:1971
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition DeclSpec.h:1094
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1242
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1091
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1115
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:2717
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
const char * getKeywordSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple keyword and contextual keyword tokens like 'int' and 'dynamic_cast'...
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h: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:56
@ TST_auto
Definition Specifiers.h:93
@ TST_bool
Definition Specifiers.h:76
@ TST_unknown_anytype
Definition Specifiers.h:96
@ TST_decltype_auto
Definition Specifiers.h:94
bool doesKeywordAttributeTakeArgs(tok::TokenKind Kind)
ImplicitTypenameContext
Definition DeclSpec.h:1904
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ NotAttributeSpecifier
This is not an attribute specifier.
Definition Parser.h:159
@ AttributeSpecifier
This should be treated as an attribute-specifier.
Definition Parser.h:161
@ InvalidAttributeSpecifier
The next tokens are '[[', but this is not an attribute-specifier.
Definition Parser.h:164
@ 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:1025
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:128
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
llvm::SmallVector< ArgsUnion, 12U > ArgsVector
Definition ParsedAttr.h:104
Language
The language for the input, used to select and validate the language standard and possible actions.
DeclaratorContext
Definition DeclSpec.h:1871
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
@ 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:1250
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:2249
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:1441
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1416
static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc, SourceLocation ConstQualLoc, SourceLocation VolatileQualLoc, SourceLocation RestrictQualLoc, SourceLocation AtomicQualLoc, SourceLocation UnalignedQualLoc, SourceLocation OverflowBehaviorLoc={}, bool OverflowBehaviorIsWrap=false)
Return a DeclaratorChunk for a pointer.
Definition DeclSpec.h:1680
static DeclaratorChunk getBlockPointer(unsigned TypeQuals, SourceLocation Loc)
Return a DeclaratorChunk for a block.
Definition DeclSpec.h:1758
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:1768
static DeclaratorChunk getArray(unsigned TypeQuals, bool isStatic, bool isStar, Expr *NumElts, SourceLocation LBLoc, SourceLocation RBLoc)
Return a DeclaratorChunk for an array.
Definition DeclSpec.h:1715
SourceLocation Loc
Loc - The place where this type was defined.
Definition DeclSpec.h:1264
static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS, unsigned TypeQuals, SourceLocation StarLoc, SourceLocation EndLoc)
Definition DeclSpec.h:1777
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
static DeclaratorChunk getParen(SourceLocation LParenLoc, SourceLocation RParenLoc)
Return a DeclaratorChunk for a paren.
Definition DeclSpec.h:1793
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1704
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:6907
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.