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