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