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