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