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