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