clang  16.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"
22 #include "clang/Parse/Parser.h"
24 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringSwitch.h"
32 
33 using namespace clang;
34 
35 //===----------------------------------------------------------------------===//
36 // C99 6.7: Declarations.
37 //===----------------------------------------------------------------------===//
38 
39 /// ParseTypeName
40 /// type-name: [C99 6.7.6]
41 /// specifier-qualifier-list abstract-declarator[opt]
42 ///
43 /// Called type-id in C++.
45  AccessSpecifier AS, Decl **OwnedType,
46  ParsedAttributes *Attrs) {
47  DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
48  if (DSC == DeclSpecContext::DSC_normal)
49  DSC = DeclSpecContext::DSC_type_specifier;
50 
51  // Parse the common declaration-specifiers piece.
52  DeclSpec DS(AttrFactory);
53  if (Attrs)
54  DS.addAttributes(*Attrs);
55  ParseSpecifierQualifierList(DS, AS, DSC);
56  if (OwnedType)
57  *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
58 
59  // Parse the abstract-declarator, if present.
60  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
61  ParseDeclarator(DeclaratorInfo);
62  if (Range)
63  *Range = DeclaratorInfo.getSourceRange();
64 
65  if (DeclaratorInfo.isInvalidType())
66  return true;
67 
68  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
69 }
70 
71 /// Normalizes an attribute name by dropping prefixed and suffixed __.
72 static StringRef normalizeAttrName(StringRef Name) {
73  if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
74  return Name.drop_front(2).drop_back(2);
75  return Name;
76 }
77 
78 /// isAttributeLateParsed - Return true if the attribute has arguments that
79 /// require late parsing.
80 static bool isAttributeLateParsed(const IdentifierInfo &II) {
81 #define CLANG_ATTR_LATE_PARSED_LIST
82  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
83 #include "clang/Parse/AttrParserStringSwitches.inc"
84  .Default(false);
85 #undef CLANG_ATTR_LATE_PARSED_LIST
86 }
87 
88 /// Check if the a start and end source location expand to the same macro.
90  SourceLocation EndLoc) {
91  if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
92  return false;
93 
95  if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
96  return false;
97 
98  bool AttrStartIsInMacro =
100  bool AttrEndIsInMacro =
102  return AttrStartIsInMacro && AttrEndIsInMacro;
103 }
104 
105 void Parser::ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs,
106  LateParsedAttrList *LateAttrs) {
107  bool MoreToParse;
108  do {
109  // Assume there's nothing left to parse, but if any attributes are in fact
110  // parsed, loop to ensure all specified attribute combinations are parsed.
111  MoreToParse = false;
112  if (WhichAttrKinds & PAKM_CXX11)
113  MoreToParse |= MaybeParseCXX11Attributes(Attrs);
114  if (WhichAttrKinds & PAKM_GNU)
115  MoreToParse |= MaybeParseGNUAttributes(Attrs, LateAttrs);
116  if (WhichAttrKinds & PAKM_Declspec)
117  MoreToParse |= MaybeParseMicrosoftDeclSpecs(Attrs);
118  } while (MoreToParse);
119 }
120 
121 /// ParseGNUAttributes - Parse a non-empty attributes list.
122 ///
123 /// [GNU] attributes:
124 /// attribute
125 /// attributes attribute
126 ///
127 /// [GNU] attribute:
128 /// '__attribute__' '(' '(' attribute-list ')' ')'
129 ///
130 /// [GNU] attribute-list:
131 /// attrib
132 /// attribute_list ',' attrib
133 ///
134 /// [GNU] attrib:
135 /// empty
136 /// attrib-name
137 /// attrib-name '(' identifier ')'
138 /// attrib-name '(' identifier ',' nonempty-expr-list ')'
139 /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
140 ///
141 /// [GNU] attrib-name:
142 /// identifier
143 /// typespec
144 /// typequal
145 /// storageclass
146 ///
147 /// Whether an attribute takes an 'identifier' is determined by the
148 /// attrib-name. GCC's behavior here is not worth imitating:
149 ///
150 /// * In C mode, if the attribute argument list starts with an identifier
151 /// followed by a ',' or an ')', and the identifier doesn't resolve to
152 /// a type, it is parsed as an identifier. If the attribute actually
153 /// wanted an expression, it's out of luck (but it turns out that no
154 /// attributes work that way, because C constant expressions are very
155 /// limited).
156 /// * In C++ mode, if the attribute argument list starts with an identifier,
157 /// and the attribute *wants* an identifier, it is parsed as an identifier.
158 /// At block scope, any additional tokens between the identifier and the
159 /// ',' or ')' are ignored, otherwise they produce a parse error.
160 ///
161 /// We follow the C++ model, but don't allow junk after the identifier.
162 void Parser::ParseGNUAttributes(ParsedAttributes &Attrs,
163  LateParsedAttrList *LateAttrs, Declarator *D) {
164  assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
165 
166  SourceLocation StartLoc = Tok.getLocation();
167  SourceLocation EndLoc = StartLoc;
168 
169  while (Tok.is(tok::kw___attribute)) {
170  SourceLocation AttrTokLoc = ConsumeToken();
171  unsigned OldNumAttrs = Attrs.size();
172  unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
173 
174  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
175  "attribute")) {
176  SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
177  return;
178  }
179  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
180  SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
181  return;
182  }
183  // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
184  do {
185  // Eat preceeding commas to allow __attribute__((,,,foo))
186  while (TryConsumeToken(tok::comma))
187  ;
188 
189  // Expect an identifier or declaration specifier (const, int, etc.)
190  if (Tok.isAnnotation())
191  break;
192  if (Tok.is(tok::code_completion)) {
193  cutOffParsing();
194  Actions.CodeCompleteAttribute(AttributeCommonInfo::Syntax::AS_GNU);
195  break;
196  }
197  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
198  if (!AttrName)
199  break;
200 
201  SourceLocation AttrNameLoc = ConsumeToken();
202 
203  if (Tok.isNot(tok::l_paren)) {
204  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
206  continue;
207  }
208 
209  // Handle "parameterized" attributes
210  if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
211  ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, &EndLoc, nullptr,
213  continue;
214  }
215 
216  // Handle attributes with arguments that require late parsing.
217  LateParsedAttribute *LA =
218  new LateParsedAttribute(this, *AttrName, AttrNameLoc);
219  LateAttrs->push_back(LA);
220 
221  // Attributes in a class are parsed at the end of the class, along
222  // with other late-parsed declarations.
223  if (!ClassStack.empty() && !LateAttrs->parseSoon())
224  getCurrentClass().LateParsedDeclarations.push_back(LA);
225 
226  // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
227  // recursively consumes balanced parens.
228  LA->Toks.push_back(Tok);
229  ConsumeParen();
230  // Consume everything up to and including the matching right parens.
231  ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
232 
233  Token Eof;
234  Eof.startToken();
235  Eof.setLocation(Tok.getLocation());
236  LA->Toks.push_back(Eof);
237  } while (Tok.is(tok::comma));
238 
239  if (ExpectAndConsume(tok::r_paren))
240  SkipUntil(tok::r_paren, StopAtSemi);
241  SourceLocation Loc = Tok.getLocation();
242  if (ExpectAndConsume(tok::r_paren))
243  SkipUntil(tok::r_paren, StopAtSemi);
244  EndLoc = Loc;
245 
246  // If this was declared in a macro, attach the macro IdentifierInfo to the
247  // parsed attribute.
248  auto &SM = PP.getSourceManager();
249  if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
250  FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
251  CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
252  StringRef FoundName =
253  Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
254  IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
255 
256  for (unsigned i = OldNumAttrs; i < Attrs.size(); ++i)
257  Attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
258 
259  if (LateAttrs) {
260  for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
261  (*LateAttrs)[i]->MacroII = MacroII;
262  }
263  }
264  }
265 
266  Attrs.Range = SourceRange(StartLoc, EndLoc);
267 }
268 
269 /// Determine whether the given attribute has an identifier argument.
271 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
272  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
273 #include "clang/Parse/AttrParserStringSwitches.inc"
274  .Default(false);
275 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
276 }
277 
278 /// Determine whether the given attribute has a variadic identifier argument.
280 #define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
281  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
282 #include "clang/Parse/AttrParserStringSwitches.inc"
283  .Default(false);
284 #undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
285 }
286 
287 /// Determine whether the given attribute treats kw_this as an identifier.
289 #define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
290  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
291 #include "clang/Parse/AttrParserStringSwitches.inc"
292  .Default(false);
293 #undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
294 }
295 
296 /// Determine if an attribute accepts parameter packs.
297 static bool attributeAcceptsExprPack(const IdentifierInfo &II) {
298 #define CLANG_ATTR_ACCEPTS_EXPR_PACK
299  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
300 #include "clang/Parse/AttrParserStringSwitches.inc"
301  .Default(false);
302 #undef CLANG_ATTR_ACCEPTS_EXPR_PACK
303 }
304 
305 /// Determine whether the given attribute parses a type argument.
306 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
307 #define CLANG_ATTR_TYPE_ARG_LIST
308  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
309 #include "clang/Parse/AttrParserStringSwitches.inc"
310  .Default(false);
311 #undef CLANG_ATTR_TYPE_ARG_LIST
312 }
313 
314 /// Determine whether the given attribute requires parsing its arguments
315 /// in an unevaluated context or not.
317 #define CLANG_ATTR_ARG_CONTEXT_LIST
318  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
319 #include "clang/Parse/AttrParserStringSwitches.inc"
320  .Default(false);
321 #undef CLANG_ATTR_ARG_CONTEXT_LIST
322 }
323 
324 IdentifierLoc *Parser::ParseIdentifierLoc() {
325  assert(Tok.is(tok::identifier) && "expected an identifier");
327  Tok.getLocation(),
328  Tok.getIdentifierInfo());
329  ConsumeToken();
330  return IL;
331 }
332 
333 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
334  SourceLocation AttrNameLoc,
335  ParsedAttributes &Attrs,
336  IdentifierInfo *ScopeName,
337  SourceLocation ScopeLoc,
338  ParsedAttr::Syntax Syntax) {
339  BalancedDelimiterTracker Parens(*this, tok::l_paren);
340  Parens.consumeOpen();
341 
342  TypeResult T;
343  if (Tok.isNot(tok::r_paren))
344  T = ParseTypeName();
345 
346  if (Parens.consumeClose())
347  return;
348 
349  if (T.isInvalid())
350  return;
351 
352  if (T.isUsable())
353  Attrs.addNewTypeAttr(&AttrName,
354  SourceRange(AttrNameLoc, Parens.getCloseLocation()),
355  ScopeName, ScopeLoc, T.get(), Syntax);
356  else
357  Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
358  ScopeName, ScopeLoc, nullptr, 0, Syntax);
359 }
360 
361 unsigned Parser::ParseAttributeArgsCommon(
362  IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
363  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
364  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
365  // Ignore the left paren location for now.
366  ConsumeParen();
367 
368  bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
369  bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
370  bool AttributeHasVariadicIdentifierArg =
372 
373  // Interpret "kw_this" as an identifier if the attributed requests it.
374  if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
375  Tok.setKind(tok::identifier);
376 
377  ArgsVector ArgExprs;
378  if (Tok.is(tok::identifier)) {
379  // If this attribute wants an 'identifier' argument, make it so.
380  bool IsIdentifierArg = AttributeHasVariadicIdentifierArg ||
381  attributeHasIdentifierArg(*AttrName);
382  ParsedAttr::Kind AttrKind =
383  ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
384 
385  // If we don't know how to parse this attribute, but this is the only
386  // token in this argument, assume it's meant to be an identifier.
387  if (AttrKind == ParsedAttr::UnknownAttribute ||
388  AttrKind == ParsedAttr::IgnoredAttribute) {
389  const Token &Next = NextToken();
390  IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
391  }
392 
393  if (IsIdentifierArg)
394  ArgExprs.push_back(ParseIdentifierLoc());
395  }
396 
397  ParsedType TheParsedType;
398  if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
399  // Eat the comma.
400  if (!ArgExprs.empty())
401  ConsumeToken();
402 
403  if (AttributeIsTypeArgAttr) {
404  // FIXME: Multiple type arguments are not implemented.
406  if (T.isInvalid()) {
407  SkipUntil(tok::r_paren, StopAtSemi);
408  return 0;
409  }
410  if (T.isUsable())
411  TheParsedType = T.get();
412  } else if (AttributeHasVariadicIdentifierArg) {
413  // Parse variadic identifier arg. This can either consume identifiers or
414  // expressions. Variadic identifier args do not support parameter packs
415  // because those are typically used for attributes with enumeration
416  // arguments, and those enumerations are not something the user could
417  // express via a pack.
418  do {
419  // Interpret "kw_this" as an identifier if the attributed requests it.
420  if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
421  Tok.setKind(tok::identifier);
422 
423  ExprResult ArgExpr;
424  if (Tok.is(tok::identifier)) {
425  ArgExprs.push_back(ParseIdentifierLoc());
426  } else {
427  bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
429  Actions,
432 
433  ExprResult ArgExpr(
435 
436  if (ArgExpr.isInvalid()) {
437  SkipUntil(tok::r_paren, StopAtSemi);
438  return 0;
439  }
440  ArgExprs.push_back(ArgExpr.get());
441  }
442  // Eat the comma, move to the next argument
443  } while (TryConsumeToken(tok::comma));
444  } else {
445  // General case. Parse all available expressions.
446  bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
448  Actions, Uneval
451 
452  ExprVector ParsedExprs;
453  if (ParseExpressionList(ParsedExprs, llvm::function_ref<void()>(),
454  /*FailImmediatelyOnInvalidExpr=*/true,
455  /*EarlyTypoCorrection=*/true)) {
456  SkipUntil(tok::r_paren, StopAtSemi);
457  return 0;
458  }
459 
460  // Pack expansion must currently be explicitly supported by an attribute.
461  for (size_t I = 0; I < ParsedExprs.size(); ++I) {
462  if (!isa<PackExpansionExpr>(ParsedExprs[I]))
463  continue;
464 
465  if (!attributeAcceptsExprPack(*AttrName)) {
466  Diag(Tok.getLocation(),
467  diag::err_attribute_argument_parm_pack_not_supported)
468  << AttrName;
469  SkipUntil(tok::r_paren, StopAtSemi);
470  return 0;
471  }
472  }
473 
474  ArgExprs.insert(ArgExprs.end(), ParsedExprs.begin(), ParsedExprs.end());
475  }
476  }
477 
478  SourceLocation RParen = Tok.getLocation();
479  if (!ExpectAndConsume(tok::r_paren)) {
480  SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
481 
482  if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
483  Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
484  ScopeName, ScopeLoc, TheParsedType, Syntax);
485  } else {
486  Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
487  ArgExprs.data(), ArgExprs.size(), Syntax);
488  }
489  }
490 
491  if (EndLoc)
492  *EndLoc = RParen;
493 
494  return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
495 }
496 
497 /// Parse the arguments to a parameterized GNU attribute or
498 /// a C++11 attribute in "gnu" namespace.
499 void Parser::ParseGNUAttributeArgs(
500  IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
501  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
502  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D) {
503 
504  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
505 
506  ParsedAttr::Kind AttrKind =
507  ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
508 
509  if (AttrKind == ParsedAttr::AT_Availability) {
510  ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
511  ScopeLoc, Syntax);
512  return;
513  } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
514  ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
515  ScopeName, ScopeLoc, Syntax);
516  return;
517  } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
518  ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
519  ScopeName, ScopeLoc, Syntax);
520  return;
521  } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
522  ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
523  ScopeLoc, Syntax);
524  return;
525  } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
526  ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
527  ScopeName, ScopeLoc, Syntax);
528  return;
529  } else if (attributeIsTypeArgAttr(*AttrName)) {
530  ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, ScopeName,
531  ScopeLoc, Syntax);
532  return;
533  }
534 
535  // These may refer to the function arguments, but need to be parsed early to
536  // participate in determining whether it's a redeclaration.
537  llvm::Optional<ParseScope> PrototypeScope;
538  if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
539  D && D->isFunctionDeclarator()) {
541  PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
544  for (unsigned i = 0; i != FTI.NumParams; ++i) {
545  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
547  }
548  }
549 
550  ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
551  ScopeLoc, Syntax);
552 }
553 
554 unsigned Parser::ParseClangAttributeArgs(
555  IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
556  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
557  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
558  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
559 
560  ParsedAttr::Kind AttrKind =
561  ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
562 
563  switch (AttrKind) {
564  default:
565  return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
566  ScopeName, ScopeLoc, Syntax);
567  case ParsedAttr::AT_ExternalSourceSymbol:
568  ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
569  ScopeName, ScopeLoc, Syntax);
570  break;
571  case ParsedAttr::AT_Availability:
572  ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
573  ScopeLoc, Syntax);
574  break;
575  case ParsedAttr::AT_ObjCBridgeRelated:
576  ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
577  ScopeName, ScopeLoc, Syntax);
578  break;
579  case ParsedAttr::AT_SwiftNewType:
580  ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
581  ScopeLoc, Syntax);
582  break;
583  case ParsedAttr::AT_TypeTagForDatatype:
584  ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
585  ScopeName, ScopeLoc, Syntax);
586  break;
587  }
588  return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
589 }
590 
591 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
592  SourceLocation AttrNameLoc,
593  ParsedAttributes &Attrs) {
594  unsigned ExistingAttrs = Attrs.size();
595 
596  // If the attribute isn't known, we will not attempt to parse any
597  // arguments.
598  if (!hasAttribute(AttributeCommonInfo::Syntax::AS_Declspec, nullptr, AttrName,
599  getTargetInfo(), getLangOpts())) {
600  // Eat the left paren, then skip to the ending right paren.
601  ConsumeParen();
602  SkipUntil(tok::r_paren);
603  return false;
604  }
605 
606  SourceLocation OpenParenLoc = Tok.getLocation();
607 
608  if (AttrName->getName() == "property") {
609  // The property declspec is more complex in that it can take one or two
610  // assignment expressions as a parameter, but the lhs of the assignment
611  // must be named get or put.
612 
613  BalancedDelimiterTracker T(*this, tok::l_paren);
614  T.expectAndConsume(diag::err_expected_lparen_after,
615  AttrName->getNameStart(), tok::r_paren);
616 
617  enum AccessorKind {
618  AK_Invalid = -1,
619  AK_Put = 0,
620  AK_Get = 1 // indices into AccessorNames
621  };
622  IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
623  bool HasInvalidAccessor = false;
624 
625  // Parse the accessor specifications.
626  while (true) {
627  // Stop if this doesn't look like an accessor spec.
628  if (!Tok.is(tok::identifier)) {
629  // If the user wrote a completely empty list, use a special diagnostic.
630  if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
631  AccessorNames[AK_Put] == nullptr &&
632  AccessorNames[AK_Get] == nullptr) {
633  Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
634  break;
635  }
636 
637  Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
638  break;
639  }
640 
641  AccessorKind Kind;
642  SourceLocation KindLoc = Tok.getLocation();
643  StringRef KindStr = Tok.getIdentifierInfo()->getName();
644  if (KindStr == "get") {
645  Kind = AK_Get;
646  } else if (KindStr == "put") {
647  Kind = AK_Put;
648 
649  // Recover from the common mistake of using 'set' instead of 'put'.
650  } else if (KindStr == "set") {
651  Diag(KindLoc, diag::err_ms_property_has_set_accessor)
652  << FixItHint::CreateReplacement(KindLoc, "put");
653  Kind = AK_Put;
654 
655  // Handle the mistake of forgetting the accessor kind by skipping
656  // this accessor.
657  } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
658  Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
659  ConsumeToken();
660  HasInvalidAccessor = true;
661  goto next_property_accessor;
662 
663  // Otherwise, complain about the unknown accessor kind.
664  } else {
665  Diag(KindLoc, diag::err_ms_property_unknown_accessor);
666  HasInvalidAccessor = true;
667  Kind = AK_Invalid;
668 
669  // Try to keep parsing unless it doesn't look like an accessor spec.
670  if (!NextToken().is(tok::equal))
671  break;
672  }
673 
674  // Consume the identifier.
675  ConsumeToken();
676 
677  // Consume the '='.
678  if (!TryConsumeToken(tok::equal)) {
679  Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
680  << KindStr;
681  break;
682  }
683 
684  // Expect the method name.
685  if (!Tok.is(tok::identifier)) {
686  Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
687  break;
688  }
689 
690  if (Kind == AK_Invalid) {
691  // Just drop invalid accessors.
692  } else if (AccessorNames[Kind] != nullptr) {
693  // Complain about the repeated accessor, ignore it, and keep parsing.
694  Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
695  } else {
696  AccessorNames[Kind] = Tok.getIdentifierInfo();
697  }
698  ConsumeToken();
699 
700  next_property_accessor:
701  // Keep processing accessors until we run out.
702  if (TryConsumeToken(tok::comma))
703  continue;
704 
705  // If we run into the ')', stop without consuming it.
706  if (Tok.is(tok::r_paren))
707  break;
708 
709  Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
710  break;
711  }
712 
713  // Only add the property attribute if it was well-formed.
714  if (!HasInvalidAccessor)
715  Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
716  AccessorNames[AK_Get], AccessorNames[AK_Put],
718  T.skipToEnd();
719  return !HasInvalidAccessor;
720  }
721 
722  unsigned NumArgs =
723  ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
725 
726  // If this attribute's args were parsed, and it was expected to have
727  // arguments but none were provided, emit a diagnostic.
728  if (ExistingAttrs < Attrs.size() && Attrs.back().getMaxArgs() && !NumArgs) {
729  Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
730  return false;
731  }
732  return true;
733 }
734 
735 /// [MS] decl-specifier:
736 /// __declspec ( extended-decl-modifier-seq )
737 ///
738 /// [MS] extended-decl-modifier-seq:
739 /// extended-decl-modifier[opt]
740 /// extended-decl-modifier extended-decl-modifier-seq
741 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs) {
742  assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
743  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
744 
745  SourceLocation StartLoc = Tok.getLocation();
746  SourceLocation EndLoc = StartLoc;
747 
748  while (Tok.is(tok::kw___declspec)) {
749  ConsumeToken();
750  BalancedDelimiterTracker T(*this, tok::l_paren);
751  if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
752  tok::r_paren))
753  return;
754 
755  // An empty declspec is perfectly legal and should not warn. Additionally,
756  // you can specify multiple attributes per declspec.
757  while (Tok.isNot(tok::r_paren)) {
758  // Attribute not present.
759  if (TryConsumeToken(tok::comma))
760  continue;
761 
762  if (Tok.is(tok::code_completion)) {
763  cutOffParsing();
765  return;
766  }
767 
768  // We expect either a well-known identifier or a generic string. Anything
769  // else is a malformed declspec.
770  bool IsString = Tok.getKind() == tok::string_literal;
771  if (!IsString && Tok.getKind() != tok::identifier &&
772  Tok.getKind() != tok::kw_restrict) {
773  Diag(Tok, diag::err_ms_declspec_type);
774  T.skipToEnd();
775  return;
776  }
777 
778  IdentifierInfo *AttrName;
779  SourceLocation AttrNameLoc;
780  if (IsString) {
781  SmallString<8> StrBuffer;
782  bool Invalid = false;
783  StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
784  if (Invalid) {
785  T.skipToEnd();
786  return;
787  }
788  AttrName = PP.getIdentifierInfo(Str);
789  AttrNameLoc = ConsumeStringToken();
790  } else {
791  AttrName = Tok.getIdentifierInfo();
792  AttrNameLoc = ConsumeToken();
793  }
794 
795  bool AttrHandled = false;
796 
797  // Parse attribute arguments.
798  if (Tok.is(tok::l_paren))
799  AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
800  else if (AttrName->getName() == "property")
801  // The property attribute must have an argument list.
802  Diag(Tok.getLocation(), diag::err_expected_lparen_after)
803  << AttrName->getName();
804 
805  if (!AttrHandled)
806  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
808  }
809  T.consumeClose();
810  EndLoc = T.getCloseLocation();
811  }
812 
813  Attrs.Range = SourceRange(StartLoc, EndLoc);
814 }
815 
816 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
817  // Treat these like attributes
818  while (true) {
819  switch (Tok.getKind()) {
820  case tok::kw___fastcall:
821  case tok::kw___stdcall:
822  case tok::kw___thiscall:
823  case tok::kw___regcall:
824  case tok::kw___cdecl:
825  case tok::kw___vectorcall:
826  case tok::kw___ptr64:
827  case tok::kw___w64:
828  case tok::kw___ptr32:
829  case tok::kw___sptr:
830  case tok::kw___uptr: {
831  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
832  SourceLocation AttrNameLoc = ConsumeToken();
833  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
835  break;
836  }
837  default:
838  return;
839  }
840  }
841 }
842 
843 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
844  SourceLocation StartLoc = Tok.getLocation();
845  SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
846 
847  if (EndLoc.isValid()) {
848  SourceRange Range(StartLoc, EndLoc);
849  Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
850  }
851 }
852 
853 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
854  SourceLocation EndLoc;
855 
856  while (true) {
857  switch (Tok.getKind()) {
858  case tok::kw_const:
859  case tok::kw_volatile:
860  case tok::kw___fastcall:
861  case tok::kw___stdcall:
862  case tok::kw___thiscall:
863  case tok::kw___cdecl:
864  case tok::kw___vectorcall:
865  case tok::kw___ptr32:
866  case tok::kw___ptr64:
867  case tok::kw___w64:
868  case tok::kw___unaligned:
869  case tok::kw___sptr:
870  case tok::kw___uptr:
871  EndLoc = ConsumeToken();
872  break;
873  default:
874  return EndLoc;
875  }
876  }
877 }
878 
879 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
880  // Treat these like attributes
881  while (Tok.is(tok::kw___pascal)) {
882  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
883  SourceLocation AttrNameLoc = ConsumeToken();
884  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
886  }
887 }
888 
889 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
890  // Treat these like attributes
891  while (Tok.is(tok::kw___kernel)) {
892  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
893  SourceLocation AttrNameLoc = ConsumeToken();
894  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
896  }
897 }
898 
899 void Parser::ParseCUDAFunctionAttributes(ParsedAttributes &attrs) {
900  while (Tok.is(tok::kw___noinline__)) {
901  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
902  SourceLocation AttrNameLoc = ConsumeToken();
903  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
905  }
906 }
907 
908 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
909  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
910  SourceLocation AttrNameLoc = Tok.getLocation();
911  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
913 }
914 
915 bool Parser::isHLSLQualifier(const Token &Tok) const {
916  return Tok.is(tok::kw_groupshared);
917 }
918 
919 void Parser::ParseHLSLQualifiers(ParsedAttributes &Attrs) {
920  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
921  SourceLocation AttrNameLoc = ConsumeToken();
922  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
924 }
925 
926 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
927  // Treat these like attributes, even though they're type specifiers.
928  while (true) {
929  switch (Tok.getKind()) {
930  case tok::kw__Nonnull:
931  case tok::kw__Nullable:
932  case tok::kw__Nullable_result:
933  case tok::kw__Null_unspecified: {
934  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
935  SourceLocation AttrNameLoc = ConsumeToken();
936  if (!getLangOpts().ObjC)
937  Diag(AttrNameLoc, diag::ext_nullability)
938  << AttrName;
939  attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
941  break;
942  }
943  default:
944  return;
945  }
946  }
947 }
948 
949 static bool VersionNumberSeparator(const char Separator) {
950  return (Separator == '.' || Separator == '_');
951 }
952 
953 /// Parse a version number.
954 ///
955 /// version:
956 /// simple-integer
957 /// simple-integer '.' simple-integer
958 /// simple-integer '_' simple-integer
959 /// simple-integer '.' simple-integer '.' simple-integer
960 /// simple-integer '_' simple-integer '_' simple-integer
961 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
962  Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
963 
964  if (!Tok.is(tok::numeric_constant)) {
965  Diag(Tok, diag::err_expected_version);
966  SkipUntil(tok::comma, tok::r_paren,
968  return VersionTuple();
969  }
970 
971  // Parse the major (and possibly minor and subminor) versions, which
972  // are stored in the numeric constant. We utilize a quirk of the
973  // lexer, which is that it handles something like 1.2.3 as a single
974  // numeric constant, rather than two separate tokens.
975  SmallString<512> Buffer;
976  Buffer.resize(Tok.getLength()+1);
977  const char *ThisTokBegin = &Buffer[0];
978 
979  // Get the spelling of the token, which eliminates trigraphs, etc.
980  bool Invalid = false;
981  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
982  if (Invalid)
983  return VersionTuple();
984 
985  // Parse the major version.
986  unsigned AfterMajor = 0;
987  unsigned Major = 0;
988  while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
989  Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
990  ++AfterMajor;
991  }
992 
993  if (AfterMajor == 0) {
994  Diag(Tok, diag::err_expected_version);
995  SkipUntil(tok::comma, tok::r_paren,
997  return VersionTuple();
998  }
999 
1000  if (AfterMajor == ActualLength) {
1001  ConsumeToken();
1002 
1003  // We only had a single version component.
1004  if (Major == 0) {
1005  Diag(Tok, diag::err_zero_version);
1006  return VersionTuple();
1007  }
1008 
1009  return VersionTuple(Major);
1010  }
1011 
1012  const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
1013  if (!VersionNumberSeparator(AfterMajorSeparator)
1014  || (AfterMajor + 1 == ActualLength)) {
1015  Diag(Tok, diag::err_expected_version);
1016  SkipUntil(tok::comma, tok::r_paren,
1018  return VersionTuple();
1019  }
1020 
1021  // Parse the minor version.
1022  unsigned AfterMinor = AfterMajor + 1;
1023  unsigned Minor = 0;
1024  while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
1025  Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
1026  ++AfterMinor;
1027  }
1028 
1029  if (AfterMinor == ActualLength) {
1030  ConsumeToken();
1031 
1032  // We had major.minor.
1033  if (Major == 0 && Minor == 0) {
1034  Diag(Tok, diag::err_zero_version);
1035  return VersionTuple();
1036  }
1037 
1038  return VersionTuple(Major, Minor);
1039  }
1040 
1041  const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
1042  // If what follows is not a '.' or '_', we have a problem.
1043  if (!VersionNumberSeparator(AfterMinorSeparator)) {
1044  Diag(Tok, diag::err_expected_version);
1045  SkipUntil(tok::comma, tok::r_paren,
1047  return VersionTuple();
1048  }
1049 
1050  // Warn if separators, be it '.' or '_', do not match.
1051  if (AfterMajorSeparator != AfterMinorSeparator)
1052  Diag(Tok, diag::warn_expected_consistent_version_separator);
1053 
1054  // Parse the subminor version.
1055  unsigned AfterSubminor = AfterMinor + 1;
1056  unsigned Subminor = 0;
1057  while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
1058  Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
1059  ++AfterSubminor;
1060  }
1061 
1062  if (AfterSubminor != ActualLength) {
1063  Diag(Tok, diag::err_expected_version);
1064  SkipUntil(tok::comma, tok::r_paren,
1066  return VersionTuple();
1067  }
1068  ConsumeToken();
1069  return VersionTuple(Major, Minor, Subminor);
1070 }
1071 
1072 /// Parse the contents of the "availability" attribute.
1073 ///
1074 /// availability-attribute:
1075 /// 'availability' '(' platform ',' opt-strict version-arg-list,
1076 /// opt-replacement, opt-message')'
1077 ///
1078 /// platform:
1079 /// identifier
1080 ///
1081 /// opt-strict:
1082 /// 'strict' ','
1083 ///
1084 /// version-arg-list:
1085 /// version-arg
1086 /// version-arg ',' version-arg-list
1087 ///
1088 /// version-arg:
1089 /// 'introduced' '=' version
1090 /// 'deprecated' '=' version
1091 /// 'obsoleted' = version
1092 /// 'unavailable'
1093 /// opt-replacement:
1094 /// 'replacement' '=' <string>
1095 /// opt-message:
1096 /// 'message' '=' <string>
1097 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
1098  SourceLocation AvailabilityLoc,
1099  ParsedAttributes &attrs,
1100  SourceLocation *endLoc,
1101  IdentifierInfo *ScopeName,
1102  SourceLocation ScopeLoc,
1103  ParsedAttr::Syntax Syntax) {
1104  enum { Introduced, Deprecated, Obsoleted, Unknown };
1105  AvailabilityChange Changes[Unknown];
1106  ExprResult MessageExpr, ReplacementExpr;
1107 
1108  // Opening '('.
1109  BalancedDelimiterTracker T(*this, tok::l_paren);
1110  if (T.consumeOpen()) {
1111  Diag(Tok, diag::err_expected) << tok::l_paren;
1112  return;
1113  }
1114 
1115  // Parse the platform name.
1116  if (Tok.isNot(tok::identifier)) {
1117  Diag(Tok, diag::err_availability_expected_platform);
1118  SkipUntil(tok::r_paren, StopAtSemi);
1119  return;
1120  }
1121  IdentifierLoc *Platform = ParseIdentifierLoc();
1122  if (const IdentifierInfo *const Ident = Platform->Ident) {
1123  // Canonicalize platform name from "macosx" to "macos".
1124  if (Ident->getName() == "macosx")
1125  Platform->Ident = PP.getIdentifierInfo("macos");
1126  // Canonicalize platform name from "macosx_app_extension" to
1127  // "macos_app_extension".
1128  else if (Ident->getName() == "macosx_app_extension")
1129  Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1130  else
1131  Platform->Ident = PP.getIdentifierInfo(
1132  AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1133  }
1134 
1135  // Parse the ',' following the platform name.
1136  if (ExpectAndConsume(tok::comma)) {
1137  SkipUntil(tok::r_paren, StopAtSemi);
1138  return;
1139  }
1140 
1141  // If we haven't grabbed the pointers for the identifiers
1142  // "introduced", "deprecated", and "obsoleted", do so now.
1143  if (!Ident_introduced) {
1144  Ident_introduced = PP.getIdentifierInfo("introduced");
1145  Ident_deprecated = PP.getIdentifierInfo("deprecated");
1146  Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1147  Ident_unavailable = PP.getIdentifierInfo("unavailable");
1148  Ident_message = PP.getIdentifierInfo("message");
1149  Ident_strict = PP.getIdentifierInfo("strict");
1150  Ident_replacement = PP.getIdentifierInfo("replacement");
1151  }
1152 
1153  // Parse the optional "strict", the optional "replacement" and the set of
1154  // introductions/deprecations/removals.
1155  SourceLocation UnavailableLoc, StrictLoc;
1156  do {
1157  if (Tok.isNot(tok::identifier)) {
1158  Diag(Tok, diag::err_availability_expected_change);
1159  SkipUntil(tok::r_paren, StopAtSemi);
1160  return;
1161  }
1162  IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1163  SourceLocation KeywordLoc = ConsumeToken();
1164 
1165  if (Keyword == Ident_strict) {
1166  if (StrictLoc.isValid()) {
1167  Diag(KeywordLoc, diag::err_availability_redundant)
1168  << Keyword << SourceRange(StrictLoc);
1169  }
1170  StrictLoc = KeywordLoc;
1171  continue;
1172  }
1173 
1174  if (Keyword == Ident_unavailable) {
1175  if (UnavailableLoc.isValid()) {
1176  Diag(KeywordLoc, diag::err_availability_redundant)
1177  << Keyword << SourceRange(UnavailableLoc);
1178  }
1179  UnavailableLoc = KeywordLoc;
1180  continue;
1181  }
1182 
1183  if (Keyword == Ident_deprecated && Platform->Ident &&
1184  Platform->Ident->isStr("swift")) {
1185  // For swift, we deprecate for all versions.
1186  if (Changes[Deprecated].KeywordLoc.isValid()) {
1187  Diag(KeywordLoc, diag::err_availability_redundant)
1188  << Keyword
1189  << SourceRange(Changes[Deprecated].KeywordLoc);
1190  }
1191 
1192  Changes[Deprecated].KeywordLoc = KeywordLoc;
1193  // Use a fake version here.
1194  Changes[Deprecated].Version = VersionTuple(1);
1195  continue;
1196  }
1197 
1198  if (Tok.isNot(tok::equal)) {
1199  Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1200  SkipUntil(tok::r_paren, StopAtSemi);
1201  return;
1202  }
1203  ConsumeToken();
1204  if (Keyword == Ident_message || Keyword == Ident_replacement) {
1205  if (Tok.isNot(tok::string_literal)) {
1206  Diag(Tok, diag::err_expected_string_literal)
1207  << /*Source='availability attribute'*/2;
1208  SkipUntil(tok::r_paren, StopAtSemi);
1209  return;
1210  }
1211  if (Keyword == Ident_message)
1212  MessageExpr = ParseStringLiteralExpression();
1213  else
1214  ReplacementExpr = ParseStringLiteralExpression();
1215  // Also reject wide string literals.
1216  if (StringLiteral *MessageStringLiteral =
1217  cast_or_null<StringLiteral>(MessageExpr.get())) {
1218  if (!MessageStringLiteral->isOrdinary()) {
1219  Diag(MessageStringLiteral->getSourceRange().getBegin(),
1220  diag::err_expected_string_literal)
1221  << /*Source='availability attribute'*/ 2;
1222  SkipUntil(tok::r_paren, StopAtSemi);
1223  return;
1224  }
1225  }
1226  if (Keyword == Ident_message)
1227  break;
1228  else
1229  continue;
1230  }
1231 
1232  // Special handling of 'NA' only when applied to introduced or
1233  // deprecated.
1234  if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1235  Tok.is(tok::identifier)) {
1236  IdentifierInfo *NA = Tok.getIdentifierInfo();
1237  if (NA->getName() == "NA") {
1238  ConsumeToken();
1239  if (Keyword == Ident_introduced)
1240  UnavailableLoc = KeywordLoc;
1241  continue;
1242  }
1243  }
1244 
1245  SourceRange VersionRange;
1246  VersionTuple Version = ParseVersionTuple(VersionRange);
1247 
1248  if (Version.empty()) {
1249  SkipUntil(tok::r_paren, StopAtSemi);
1250  return;
1251  }
1252 
1253  unsigned Index;
1254  if (Keyword == Ident_introduced)
1255  Index = Introduced;
1256  else if (Keyword == Ident_deprecated)
1257  Index = Deprecated;
1258  else if (Keyword == Ident_obsoleted)
1259  Index = Obsoleted;
1260  else
1261  Index = Unknown;
1262 
1263  if (Index < Unknown) {
1264  if (!Changes[Index].KeywordLoc.isInvalid()) {
1265  Diag(KeywordLoc, diag::err_availability_redundant)
1266  << Keyword
1267  << SourceRange(Changes[Index].KeywordLoc,
1268  Changes[Index].VersionRange.getEnd());
1269  }
1270 
1271  Changes[Index].KeywordLoc = KeywordLoc;
1272  Changes[Index].Version = Version;
1273  Changes[Index].VersionRange = VersionRange;
1274  } else {
1275  Diag(KeywordLoc, diag::err_availability_unknown_change)
1276  << Keyword << VersionRange;
1277  }
1278 
1279  } while (TryConsumeToken(tok::comma));
1280 
1281  // Closing ')'.
1282  if (T.consumeClose())
1283  return;
1284 
1285  if (endLoc)
1286  *endLoc = T.getCloseLocation();
1287 
1288  // The 'unavailable' availability cannot be combined with any other
1289  // availability changes. Make sure that hasn't happened.
1290  if (UnavailableLoc.isValid()) {
1291  bool Complained = false;
1292  for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1293  if (Changes[Index].KeywordLoc.isValid()) {
1294  if (!Complained) {
1295  Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1296  << SourceRange(Changes[Index].KeywordLoc,
1297  Changes[Index].VersionRange.getEnd());
1298  Complained = true;
1299  }
1300 
1301  // Clear out the availability.
1302  Changes[Index] = AvailabilityChange();
1303  }
1304  }
1305  }
1306 
1307  // Record this attribute
1308  attrs.addNew(&Availability,
1309  SourceRange(AvailabilityLoc, T.getCloseLocation()),
1310  ScopeName, ScopeLoc,
1311  Platform,
1312  Changes[Introduced],
1313  Changes[Deprecated],
1314  Changes[Obsoleted],
1315  UnavailableLoc, MessageExpr.get(),
1316  Syntax, StrictLoc, ReplacementExpr.get());
1317 }
1318 
1319 /// Parse the contents of the "external_source_symbol" attribute.
1320 ///
1321 /// external-source-symbol-attribute:
1322 /// 'external_source_symbol' '(' keyword-arg-list ')'
1323 ///
1324 /// keyword-arg-list:
1325 /// keyword-arg
1326 /// keyword-arg ',' keyword-arg-list
1327 ///
1328 /// keyword-arg:
1329 /// 'language' '=' <string>
1330 /// 'defined_in' '=' <string>
1331 /// 'generated_declaration'
1332 void Parser::ParseExternalSourceSymbolAttribute(
1333  IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1334  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1335  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1336  // Opening '('.
1337  BalancedDelimiterTracker T(*this, tok::l_paren);
1338  if (T.expectAndConsume())
1339  return;
1340 
1341  // Initialize the pointers for the keyword identifiers when required.
1342  if (!Ident_language) {
1343  Ident_language = PP.getIdentifierInfo("language");
1344  Ident_defined_in = PP.getIdentifierInfo("defined_in");
1345  Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1346  }
1347 
1349  bool HasLanguage = false;
1350  ExprResult DefinedInExpr;
1351  bool HasDefinedIn = false;
1352  IdentifierLoc *GeneratedDeclaration = nullptr;
1353 
1354  // Parse the language/defined_in/generated_declaration keywords
1355  do {
1356  if (Tok.isNot(tok::identifier)) {
1357  Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1358  SkipUntil(tok::r_paren, StopAtSemi);
1359  return;
1360  }
1361 
1362  SourceLocation KeywordLoc = Tok.getLocation();
1363  IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1364  if (Keyword == Ident_generated_declaration) {
1365  if (GeneratedDeclaration) {
1366  Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1367  SkipUntil(tok::r_paren, StopAtSemi);
1368  return;
1369  }
1370  GeneratedDeclaration = ParseIdentifierLoc();
1371  continue;
1372  }
1373 
1374  if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1375  Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1376  SkipUntil(tok::r_paren, StopAtSemi);
1377  return;
1378  }
1379 
1380  ConsumeToken();
1381  if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1382  Keyword->getName())) {
1383  SkipUntil(tok::r_paren, StopAtSemi);
1384  return;
1385  }
1386 
1387  bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1388  if (Keyword == Ident_language)
1389  HasLanguage = true;
1390  else
1391  HasDefinedIn = true;
1392 
1393  if (Tok.isNot(tok::string_literal)) {
1394  Diag(Tok, diag::err_expected_string_literal)
1395  << /*Source='external_source_symbol attribute'*/ 3
1396  << /*language | source container*/ (Keyword != Ident_language);
1397  SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1398  continue;
1399  }
1400  if (Keyword == Ident_language) {
1401  if (HadLanguage) {
1402  Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1403  << Keyword;
1405  continue;
1406  }
1408  } else {
1409  assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1410  if (HadDefinedIn) {
1411  Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1412  << Keyword;
1414  continue;
1415  }
1416  DefinedInExpr = ParseStringLiteralExpression();
1417  }
1418  } while (TryConsumeToken(tok::comma));
1419 
1420  // Closing ')'.
1421  if (T.consumeClose())
1422  return;
1423  if (EndLoc)
1424  *EndLoc = T.getCloseLocation();
1425 
1426  ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1427  GeneratedDeclaration};
1428  Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1429  ScopeName, ScopeLoc, Args, std::size(Args), Syntax);
1430 }
1431 
1432 /// Parse the contents of the "objc_bridge_related" attribute.
1433 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1434 /// related_class:
1435 /// Identifier
1436 ///
1437 /// opt-class_method:
1438 /// Identifier: | <empty>
1439 ///
1440 /// opt-instance_method:
1441 /// Identifier | <empty>
1442 ///
1443 void Parser::ParseObjCBridgeRelatedAttribute(
1444  IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc,
1445  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1446  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1447  // Opening '('.
1448  BalancedDelimiterTracker T(*this, tok::l_paren);
1449  if (T.consumeOpen()) {
1450  Diag(Tok, diag::err_expected) << tok::l_paren;
1451  return;
1452  }
1453 
1454  // Parse the related class name.
1455  if (Tok.isNot(tok::identifier)) {
1456  Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1457  SkipUntil(tok::r_paren, StopAtSemi);
1458  return;
1459  }
1460  IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1461  if (ExpectAndConsume(tok::comma)) {
1462  SkipUntil(tok::r_paren, StopAtSemi);
1463  return;
1464  }
1465 
1466  // Parse class method name. It's non-optional in the sense that a trailing
1467  // comma is required, but it can be the empty string, and then we record a
1468  // nullptr.
1469  IdentifierLoc *ClassMethod = nullptr;
1470  if (Tok.is(tok::identifier)) {
1471  ClassMethod = ParseIdentifierLoc();
1472  if (!TryConsumeToken(tok::colon)) {
1473  Diag(Tok, diag::err_objcbridge_related_selector_name);
1474  SkipUntil(tok::r_paren, StopAtSemi);
1475  return;
1476  }
1477  }
1478  if (!TryConsumeToken(tok::comma)) {
1479  if (Tok.is(tok::colon))
1480  Diag(Tok, diag::err_objcbridge_related_selector_name);
1481  else
1482  Diag(Tok, diag::err_expected) << tok::comma;
1483  SkipUntil(tok::r_paren, StopAtSemi);
1484  return;
1485  }
1486 
1487  // Parse instance method name. Also non-optional but empty string is
1488  // permitted.
1489  IdentifierLoc *InstanceMethod = nullptr;
1490  if (Tok.is(tok::identifier))
1491  InstanceMethod = ParseIdentifierLoc();
1492  else if (Tok.isNot(tok::r_paren)) {
1493  Diag(Tok, diag::err_expected) << tok::r_paren;
1494  SkipUntil(tok::r_paren, StopAtSemi);
1495  return;
1496  }
1497 
1498  // Closing ')'.
1499  if (T.consumeClose())
1500  return;
1501 
1502  if (EndLoc)
1503  *EndLoc = T.getCloseLocation();
1504 
1505  // Record this attribute
1506  Attrs.addNew(&ObjCBridgeRelated,
1507  SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1508  ScopeName, ScopeLoc, RelatedClass, ClassMethod, InstanceMethod,
1509  Syntax);
1510 }
1511 
1512 void Parser::ParseSwiftNewTypeAttribute(
1513  IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1514  ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1515  SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1516  BalancedDelimiterTracker T(*this, tok::l_paren);
1517 
1518  // Opening '('
1519  if (T.consumeOpen()) {
1520  Diag(Tok, diag::err_expected) << tok::l_paren;
1521  return;
1522  }
1523 
1524  if (Tok.is(tok::r_paren)) {
1525  Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1526  T.consumeClose();
1527  return;
1528  }
1529  if (Tok.isNot(tok::kw_struct) && Tok.isNot(tok::kw_enum)) {
1530  Diag(Tok, diag::warn_attribute_type_not_supported)
1531  << &AttrName << Tok.getIdentifierInfo();
1532  if (!isTokenSpecial())
1533  ConsumeToken();
1534  T.consumeClose();
1535  return;
1536  }
1537 
1538  auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1539  Tok.getIdentifierInfo());
1540  ConsumeToken();
1541 
1542  // Closing ')'
1543  if (T.consumeClose())
1544  return;
1545  if (EndLoc)
1546  *EndLoc = T.getCloseLocation();
1547 
1548  ArgsUnion Args[] = {SwiftType};
1549  Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
1550  ScopeName, ScopeLoc, Args, std::size(Args), Syntax);
1551 }
1552 
1553 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1554  SourceLocation AttrNameLoc,
1555  ParsedAttributes &Attrs,
1556  SourceLocation *EndLoc,
1557  IdentifierInfo *ScopeName,
1558  SourceLocation ScopeLoc,
1559  ParsedAttr::Syntax Syntax) {
1560  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1561 
1562  BalancedDelimiterTracker T(*this, tok::l_paren);
1563  T.consumeOpen();
1564 
1565  if (Tok.isNot(tok::identifier)) {
1566  Diag(Tok, diag::err_expected) << tok::identifier;
1567  T.skipToEnd();
1568  return;
1569  }
1570  IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1571 
1572  if (ExpectAndConsume(tok::comma)) {
1573  T.skipToEnd();
1574  return;
1575  }
1576 
1577  SourceRange MatchingCTypeRange;
1578  TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1579  if (MatchingCType.isInvalid()) {
1580  T.skipToEnd();
1581  return;
1582  }
1583 
1584  bool LayoutCompatible = false;
1585  bool MustBeNull = false;
1586  while (TryConsumeToken(tok::comma)) {
1587  if (Tok.isNot(tok::identifier)) {
1588  Diag(Tok, diag::err_expected) << tok::identifier;
1589  T.skipToEnd();
1590  return;
1591  }
1592  IdentifierInfo *Flag = Tok.getIdentifierInfo();
1593  if (Flag->isStr("layout_compatible"))
1594  LayoutCompatible = true;
1595  else if (Flag->isStr("must_be_null"))
1596  MustBeNull = true;
1597  else {
1598  Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1599  T.skipToEnd();
1600  return;
1601  }
1602  ConsumeToken(); // consume flag
1603  }
1604 
1605  if (!T.consumeClose()) {
1606  Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1607  ArgumentKind, MatchingCType.get(),
1608  LayoutCompatible, MustBeNull, Syntax);
1609  }
1610 
1611  if (EndLoc)
1612  *EndLoc = T.getCloseLocation();
1613 }
1614 
1615 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1616 /// of a C++11 attribute-specifier in a location where an attribute is not
1617 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1618 /// situation.
1619 ///
1620 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1621 /// this doesn't appear to actually be an attribute-specifier, and the caller
1622 /// should try to parse it.
1623 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1624  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1625 
1626  switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1627  case CAK_NotAttributeSpecifier:
1628  // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1629  return false;
1630 
1631  case CAK_InvalidAttributeSpecifier:
1632  Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1633  return false;
1634 
1635  case CAK_AttributeSpecifier:
1636  // Parse and discard the attributes.
1637  SourceLocation BeginLoc = ConsumeBracket();
1638  ConsumeBracket();
1639  SkipUntil(tok::r_square);
1640  assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1641  SourceLocation EndLoc = ConsumeBracket();
1642  Diag(BeginLoc, diag::err_attributes_not_allowed)
1643  << SourceRange(BeginLoc, EndLoc);
1644  return true;
1645  }
1646  llvm_unreachable("All cases handled above.");
1647 }
1648 
1649 /// We have found the opening square brackets of a C++11
1650 /// attribute-specifier in a location where an attribute is not permitted, but
1651 /// we know where the attributes ought to be written. Parse them anyway, and
1652 /// provide a fixit moving them to the right place.
1653 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributes &Attrs,
1654  SourceLocation CorrectLocation) {
1655  assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1656  Tok.is(tok::kw_alignas));
1657 
1658  // Consume the attributes.
1659  SourceLocation Loc = Tok.getLocation();
1660  ParseCXX11Attributes(Attrs);
1661  CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1662  // FIXME: use err_attributes_misplaced
1663  Diag(Loc, diag::err_attributes_not_allowed)
1664  << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1665  << FixItHint::CreateRemoval(AttrRange);
1666 }
1667 
1668 void Parser::DiagnoseProhibitedAttributes(
1669  const SourceRange &Range, const SourceLocation CorrectLocation) {
1670  if (CorrectLocation.isValid()) {
1671  CharSourceRange AttrRange(Range, true);
1672  Diag(CorrectLocation, diag::err_attributes_misplaced)
1673  << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1674  << FixItHint::CreateRemoval(AttrRange);
1675  } else
1676  Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1677 }
1678 
1679 void Parser::ProhibitCXX11Attributes(ParsedAttributes &Attrs, unsigned DiagID,
1680  bool DiagnoseEmptyAttrs,
1681  bool WarnOnUnknownAttrs) {
1682 
1683  if (DiagnoseEmptyAttrs && Attrs.empty() && Attrs.Range.isValid()) {
1684  // An attribute list has been parsed, but it was empty.
1685  // This is the case for [[]].
1686  const auto &LangOpts = getLangOpts();
1687  auto &SM = PP.getSourceManager();
1688  Token FirstLSquare;
1689  Lexer::getRawToken(Attrs.Range.getBegin(), FirstLSquare, SM, LangOpts);
1690 
1691  if (FirstLSquare.is(tok::l_square)) {
1692  llvm::Optional<Token> SecondLSquare =
1693  Lexer::findNextToken(FirstLSquare.getLocation(), SM, LangOpts);
1694 
1695  if (SecondLSquare && SecondLSquare->is(tok::l_square)) {
1696  // The attribute range starts with [[, but is empty. So this must
1697  // be [[]], which we are supposed to diagnose because
1698  // DiagnoseEmptyAttrs is true.
1699  Diag(Attrs.Range.getBegin(), DiagID) << Attrs.Range;
1700  return;
1701  }
1702  }
1703  }
1704 
1705  for (const ParsedAttr &AL : Attrs) {
1706  if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1707  continue;
1708  if (AL.getKind() == ParsedAttr::UnknownAttribute) {
1709  if (WarnOnUnknownAttrs)
1710  Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1711  << AL << AL.getRange();
1712  } else {
1713  Diag(AL.getLoc(), DiagID) << AL;
1714  AL.setInvalid();
1715  }
1716  }
1717 }
1718 
1719 void Parser::DiagnoseCXX11AttributeExtension(ParsedAttributes &Attrs) {
1720  for (const ParsedAttr &PA : Attrs) {
1721  if (PA.isCXX11Attribute() || PA.isC2xAttribute())
1722  Diag(PA.getLoc(), diag::ext_cxx11_attr_placement) << PA << PA.getRange();
1723  }
1724 }
1725 
1726 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1727 // applies to var, not the type Foo.
1728 // As an exception to the rule, __declspec(align(...)) before the
1729 // class-key affects the type instead of the variable.
1730 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1731 // variable.
1732 // This function moves attributes that should apply to the type off DS to Attrs.
1733 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs,
1734  DeclSpec &DS,
1735  Sema::TagUseKind TUK) {
1736  if (TUK == Sema::TUK_Reference)
1737  return;
1738 
1740 
1741  for (ParsedAttr &AL : DS.getAttributes()) {
1742  if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1743  AL.isDeclspecAttribute()) ||
1744  AL.isMicrosoftAttribute())
1745  ToBeMoved.push_back(&AL);
1746  }
1747 
1748  for (ParsedAttr *AL : ToBeMoved) {
1749  DS.getAttributes().remove(AL);
1750  Attrs.addAtEnd(AL);
1751  }
1752 }
1753 
1754 /// ParseDeclaration - Parse a full 'declaration', which consists of
1755 /// declaration-specifiers, some number of declarators, and a semicolon.
1756 /// 'Context' should be a DeclaratorContext value. This returns the
1757 /// location of the semicolon in DeclEnd.
1758 ///
1759 /// declaration: [C99 6.7]
1760 /// block-declaration ->
1761 /// simple-declaration
1762 /// others [FIXME]
1763 /// [C++] template-declaration
1764 /// [C++] namespace-definition
1765 /// [C++] using-directive
1766 /// [C++] using-declaration
1767 /// [C++11/C11] static_assert-declaration
1768 /// others... [FIXME]
1769 ///
1770 Parser::DeclGroupPtrTy Parser::ParseDeclaration(DeclaratorContext Context,
1771  SourceLocation &DeclEnd,
1772  ParsedAttributes &DeclAttrs,
1773  ParsedAttributes &DeclSpecAttrs,
1774  SourceLocation *DeclSpecStart) {
1775  ParenBraceBracketBalancer BalancerRAIIObj(*this);
1776  // Must temporarily exit the objective-c container scope for
1777  // parsing c none objective-c decls.
1778  ObjCDeclContextSwitch ObjCDC(*this);
1779 
1780  Decl *SingleDecl = nullptr;
1781  switch (Tok.getKind()) {
1782  case tok::kw_template:
1783  case tok::kw_export:
1784  ProhibitAttributes(DeclAttrs);
1785  ProhibitAttributes(DeclSpecAttrs);
1786  SingleDecl =
1787  ParseDeclarationStartingWithTemplate(Context, DeclEnd, DeclAttrs);
1788  break;
1789  case tok::kw_inline:
1790  // Could be the start of an inline namespace. Allowed as an ext in C++03.
1791  if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1792  ProhibitAttributes(DeclAttrs);
1793  ProhibitAttributes(DeclSpecAttrs);
1794  SourceLocation InlineLoc = ConsumeToken();
1795  return ParseNamespace(Context, DeclEnd, InlineLoc);
1796  }
1797  return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1798  true, nullptr, DeclSpecStart);
1799 
1800  case tok::kw_cbuffer:
1801  case tok::kw_tbuffer:
1802  SingleDecl = ParseHLSLBuffer(DeclEnd);
1803  break;
1804  case tok::kw_namespace:
1805  ProhibitAttributes(DeclAttrs);
1806  ProhibitAttributes(DeclSpecAttrs);
1807  return ParseNamespace(Context, DeclEnd);
1808  case tok::kw_using: {
1809  ParsedAttributes Attrs(AttrFactory);
1810  takeAndConcatenateAttrs(DeclAttrs, DeclSpecAttrs, Attrs);
1811  return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1812  DeclEnd, Attrs);
1813  }
1814  case tok::kw_static_assert:
1815  case tok::kw__Static_assert:
1816  ProhibitAttributes(DeclAttrs);
1817  ProhibitAttributes(DeclSpecAttrs);
1818  SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1819  break;
1820  default:
1821  return ParseSimpleDeclaration(Context, DeclEnd, DeclAttrs, DeclSpecAttrs,
1822  true, nullptr, DeclSpecStart);
1823  }
1824 
1825  // This routine returns a DeclGroup, if the thing we parsed only contains a
1826  // single decl, convert it now.
1827  return Actions.ConvertDeclToDeclGroup(SingleDecl);
1828 }
1829 
1830 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1831 /// declaration-specifiers init-declarator-list[opt] ';'
1832 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1833 /// init-declarator-list ';'
1834 ///[C90/C++]init-declarator-list ';' [TODO]
1835 /// [OMP] threadprivate-directive
1836 /// [OMP] allocate-directive [TODO]
1837 ///
1838 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1839 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1840 ///
1841 /// If RequireSemi is false, this does not check for a ';' at the end of the
1842 /// declaration. If it is true, it checks for and eats it.
1843 ///
1844 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1845 /// of a simple-declaration. If we find that we are, we also parse the
1846 /// for-range-initializer, and place it here.
1847 ///
1848 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1849 /// the Declaration. The SourceLocation for this Decl is set to
1850 /// DeclSpecStart if DeclSpecStart is non-null.
1851 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1852  DeclaratorContext Context, SourceLocation &DeclEnd,
1853  ParsedAttributes &DeclAttrs, ParsedAttributes &DeclSpecAttrs,
1854  bool RequireSemi, ForRangeInit *FRI, SourceLocation *DeclSpecStart) {
1855  // Need to retain these for diagnostics before we add them to the DeclSepc.
1856  ParsedAttributesView OriginalDeclSpecAttrs;
1857  OriginalDeclSpecAttrs.addAll(DeclSpecAttrs.begin(), DeclSpecAttrs.end());
1858  OriginalDeclSpecAttrs.Range = DeclSpecAttrs.Range;
1859 
1860  // Parse the common declaration-specifiers piece.
1861  ParsingDeclSpec DS(*this);
1862  DS.takeAttributesFrom(DeclSpecAttrs);
1863 
1864  DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1865  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1866 
1867  // If we had a free-standing type definition with a missing semicolon, we
1868  // may get this far before the problem becomes obvious.
1869  if (DS.hasTagDefinition() &&
1870  DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1871  return nullptr;
1872 
1873  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1874  // declaration-specifiers init-declarator-list[opt] ';'
1875  if (Tok.is(tok::semi)) {
1876  ProhibitAttributes(DeclAttrs);
1877  DeclEnd = Tok.getLocation();
1878  if (RequireSemi) ConsumeToken();
1879  RecordDecl *AnonRecord = nullptr;
1880  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
1881  getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
1882  DS.complete(TheDecl);
1883  if (AnonRecord) {
1884  Decl* decls[] = {AnonRecord, TheDecl};
1885  return Actions.BuildDeclaratorGroup(decls);
1886  }
1887  return Actions.ConvertDeclToDeclGroup(TheDecl);
1888  }
1889 
1890  if (DeclSpecStart)
1891  DS.SetRangeStart(*DeclSpecStart);
1892 
1893  return ParseDeclGroup(DS, Context, DeclAttrs, &DeclEnd, FRI);
1894 }
1895 
1896 /// Returns true if this might be the start of a declarator, or a common typo
1897 /// for a declarator.
1898 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1899  switch (Tok.getKind()) {
1900  case tok::annot_cxxscope:
1901  case tok::annot_template_id:
1902  case tok::caret:
1903  case tok::code_completion:
1904  case tok::coloncolon:
1905  case tok::ellipsis:
1906  case tok::kw___attribute:
1907  case tok::kw_operator:
1908  case tok::l_paren:
1909  case tok::star:
1910  return true;
1911 
1912  case tok::amp:
1913  case tok::ampamp:
1914  return getLangOpts().CPlusPlus;
1915 
1916  case tok::l_square: // Might be an attribute on an unnamed bit-field.
1917  return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
1918  NextToken().is(tok::l_square);
1919 
1920  case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1921  return Context == DeclaratorContext::Member || getLangOpts().CPlusPlus;
1922 
1923  case tok::identifier:
1924  switch (NextToken().getKind()) {
1925  case tok::code_completion:
1926  case tok::coloncolon:
1927  case tok::comma:
1928  case tok::equal:
1929  case tok::equalequal: // Might be a typo for '='.
1930  case tok::kw_alignas:
1931  case tok::kw_asm:
1932  case tok::kw___attribute:
1933  case tok::l_brace:
1934  case tok::l_paren:
1935  case tok::l_square:
1936  case tok::less:
1937  case tok::r_brace:
1938  case tok::r_paren:
1939  case tok::r_square:
1940  case tok::semi:
1941  return true;
1942 
1943  case tok::colon:
1944  // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1945  // and in block scope it's probably a label. Inside a class definition,
1946  // this is a bit-field.
1947  return Context == DeclaratorContext::Member ||
1948  (getLangOpts().CPlusPlus && Context == DeclaratorContext::File);
1949 
1950  case tok::identifier: // Possible virt-specifier.
1951  return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1952 
1953  default:
1954  return false;
1955  }
1956 
1957  default:
1958  return false;
1959  }
1960 }
1961 
1962 /// Skip until we reach something which seems like a sensible place to pick
1963 /// up parsing after a malformed declaration. This will sometimes stop sooner
1964 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1966  while (true) {
1967  switch (Tok.getKind()) {
1968  case tok::l_brace:
1969  // Skip until matching }, then stop. We've probably skipped over
1970  // a malformed class or function definition or similar.
1971  ConsumeBrace();
1972  SkipUntil(tok::r_brace);
1973  if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1974  // This declaration isn't over yet. Keep skipping.
1975  continue;
1976  }
1977  TryConsumeToken(tok::semi);
1978  return;
1979 
1980  case tok::l_square:
1981  ConsumeBracket();
1982  SkipUntil(tok::r_square);
1983  continue;
1984 
1985  case tok::l_paren:
1986  ConsumeParen();
1987  SkipUntil(tok::r_paren);
1988  continue;
1989 
1990  case tok::r_brace:
1991  return;
1992 
1993  case tok::semi:
1994  ConsumeToken();
1995  return;
1996 
1997  case tok::kw_inline:
1998  // 'inline namespace' at the start of a line is almost certainly
1999  // a good place to pick back up parsing, except in an Objective-C
2000  // @interface context.
2001  if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
2002  (!ParsingInObjCContainer || CurParsedObjCImpl))
2003  return;
2004  break;
2005 
2006  case tok::kw_namespace:
2007  // 'namespace' at the start of a line is almost certainly a good
2008  // place to pick back up parsing, except in an Objective-C
2009  // @interface context.
2010  if (Tok.isAtStartOfLine() &&
2011  (!ParsingInObjCContainer || CurParsedObjCImpl))
2012  return;
2013  break;
2014 
2015  case tok::at:
2016  // @end is very much like } in Objective-C contexts.
2017  if (NextToken().isObjCAtKeyword(tok::objc_end) &&
2018  ParsingInObjCContainer)
2019  return;
2020  break;
2021 
2022  case tok::minus:
2023  case tok::plus:
2024  // - and + probably start new method declarations in Objective-C contexts.
2025  if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
2026  return;
2027  break;
2028 
2029  case tok::eof:
2030  case tok::annot_module_begin:
2031  case tok::annot_module_end:
2032  case tok::annot_module_include:
2033  return;
2034 
2035  default:
2036  break;
2037  }
2038 
2039  ConsumeAnyToken();
2040  }
2041 }
2042 
2043 /// ParseDeclGroup - Having concluded that this is either a function
2044 /// definition or a group of object declarations, actually parse the
2045 /// result.
2046 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2047  DeclaratorContext Context,
2048  ParsedAttributes &Attrs,
2049  SourceLocation *DeclEnd,
2050  ForRangeInit *FRI) {
2051  // Parse the first declarator.
2052  // Consume all of the attributes from `Attrs` by moving them to our own local
2053  // list. This ensures that we will not attempt to interpret them as statement
2054  // attributes higher up the callchain.
2055  ParsedAttributes LocalAttrs(AttrFactory);
2056  LocalAttrs.takeAllFrom(Attrs);
2057  ParsingDeclarator D(*this, DS, LocalAttrs, Context);
2058  ParseDeclarator(D);
2059 
2060  // Bail out if the first declarator didn't seem well-formed.
2061  if (!D.hasName() && !D.mayOmitIdentifier()) {
2063  return nullptr;
2064  }
2065 
2066  if (getLangOpts().HLSL)
2067  MaybeParseHLSLSemantics(D);
2068 
2069  if (Tok.is(tok::kw_requires))
2070  ParseTrailingRequiresClause(D);
2071 
2072  // Save late-parsed attributes for now; they need to be parsed in the
2073  // appropriate function scope after the function Decl has been constructed.
2074  // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2075  LateParsedAttrList LateParsedAttrs(true);
2076  if (D.isFunctionDeclarator()) {
2077  MaybeParseGNUAttributes(D, &LateParsedAttrs);
2078 
2079  // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2080  // attribute. If we find the keyword here, tell the user to put it
2081  // at the start instead.
2082  if (Tok.is(tok::kw__Noreturn)) {
2083  SourceLocation Loc = ConsumeToken();
2084  const char *PrevSpec;
2085  unsigned DiagID;
2086 
2087  // We can offer a fixit if it's valid to mark this function as _Noreturn
2088  // and we don't have any other declarators in this declaration.
2089  bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2090  MaybeParseGNUAttributes(D, &LateParsedAttrs);
2091  Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2092 
2093  Diag(Loc, diag::err_c11_noreturn_misplaced)
2094  << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2095  << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2096  : FixItHint());
2097  }
2098 
2099  // Check to see if we have a function *definition* which must have a body.
2100  if (Tok.is(tok::equal) && NextToken().is(tok::code_completion)) {
2101  cutOffParsing();
2103  return nullptr;
2104  }
2105  // We're at the point where the parsing of function declarator is finished.
2106  //
2107  // A common error is that users accidently add a virtual specifier
2108  // (e.g. override) in an out-line method definition.
2109  // We attempt to recover by stripping all these specifiers coming after
2110  // the declarator.
2111  while (auto Specifier = isCXX11VirtSpecifier()) {
2112  Diag(Tok, diag::err_virt_specifier_outside_class)
2115  ConsumeToken();
2116  }
2117  // Look at the next token to make sure that this isn't a function
2118  // declaration. We have to check this because __attribute__ might be the
2119  // start of a function definition in GCC-extended K&R C.
2120  if (!isDeclarationAfterDeclarator()) {
2121 
2122  // Function definitions are only allowed at file scope and in C++ classes.
2123  // The C++ inline method definition case is handled elsewhere, so we only
2124  // need to handle the file scope definition case.
2125  if (Context == DeclaratorContext::File) {
2126  if (isStartOfFunctionDefinition(D)) {
2128  Diag(Tok, diag::err_function_declared_typedef);
2129 
2130  // Recover by treating the 'typedef' as spurious.
2132  }
2133 
2134  Decl *TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
2135  &LateParsedAttrs);
2136  return Actions.ConvertDeclToDeclGroup(TheDecl);
2137  }
2138 
2139  if (isDeclarationSpecifier(ImplicitTypenameContext::No)) {
2140  // If there is an invalid declaration specifier right after the
2141  // function prototype, then we must be in a missing semicolon case
2142  // where this isn't actually a body. Just fall through into the code
2143  // that handles it as a prototype, and let the top-level code handle
2144  // the erroneous declspec where it would otherwise expect a comma or
2145  // semicolon.
2146  } else {
2147  Diag(Tok, diag::err_expected_fn_body);
2148  SkipUntil(tok::semi);
2149  return nullptr;
2150  }
2151  } else {
2152  if (Tok.is(tok::l_brace)) {
2153  Diag(Tok, diag::err_function_definition_not_allowed);
2155  return nullptr;
2156  }
2157  }
2158  }
2159  }
2160 
2161  if (ParseAsmAttributesAfterDeclarator(D))
2162  return nullptr;
2163 
2164  // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2165  // must parse and analyze the for-range-initializer before the declaration is
2166  // analyzed.
2167  //
2168  // Handle the Objective-C for-in loop variable similarly, although we
2169  // don't need to parse the container in advance.
2170  if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2171  bool IsForRangeLoop = false;
2172  if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2173  IsForRangeLoop = true;
2174  if (getLangOpts().OpenMP)
2175  Actions.startOpenMPCXXRangeFor();
2176  if (Tok.is(tok::l_brace))
2177  FRI->RangeExpr = ParseBraceInitializer();
2178  else
2179  FRI->RangeExpr = ParseExpression();
2180  }
2181 
2182  Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2183  if (IsForRangeLoop) {
2184  Actions.ActOnCXXForRangeDecl(ThisDecl);
2185  } else {
2186  // Obj-C for loop
2187  if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2188  VD->setObjCForDecl(true);
2189  }
2190  Actions.FinalizeDeclaration(ThisDecl);
2191  D.complete(ThisDecl);
2192  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2193  }
2194 
2195  SmallVector<Decl *, 8> DeclsInGroup;
2196  Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2197  D, ParsedTemplateInfo(), FRI);
2198  if (LateParsedAttrs.size() > 0)
2199  ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2200  D.complete(FirstDecl);
2201  if (FirstDecl)
2202  DeclsInGroup.push_back(FirstDecl);
2203 
2204  bool ExpectSemi = Context != DeclaratorContext::ForInit;
2205 
2206  // If we don't have a comma, it is either the end of the list (a ';') or an
2207  // error, bail out.
2208  SourceLocation CommaLoc;
2209  while (TryConsumeToken(tok::comma, CommaLoc)) {
2210  if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2211  // This comma was followed by a line-break and something which can't be
2212  // the start of a declarator. The comma was probably a typo for a
2213  // semicolon.
2214  Diag(CommaLoc, diag::err_expected_semi_declaration)
2215  << FixItHint::CreateReplacement(CommaLoc, ";");
2216  ExpectSemi = false;
2217  break;
2218  }
2219 
2220  // Parse the next declarator.
2221  D.clear();
2222  D.setCommaLoc(CommaLoc);
2223 
2224  // Accept attributes in an init-declarator. In the first declarator in a
2225  // declaration, these would be part of the declspec. In subsequent
2226  // declarators, they become part of the declarator itself, so that they
2227  // don't apply to declarators after *this* one. Examples:
2228  // short __attribute__((common)) var; -> declspec
2229  // short var __attribute__((common)); -> declarator
2230  // short x, __attribute__((common)) var; -> declarator
2231  MaybeParseGNUAttributes(D);
2232 
2233  // MSVC parses but ignores qualifiers after the comma as an extension.
2234  if (getLangOpts().MicrosoftExt)
2235  DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2236 
2237  ParseDeclarator(D);
2238 
2239  if (getLangOpts().HLSL)
2240  MaybeParseHLSLSemantics(D);
2241 
2242  if (!D.isInvalidType()) {
2243  // C++2a [dcl.decl]p1
2244  // init-declarator:
2245  // declarator initializer[opt]
2246  // declarator requires-clause
2247  if (Tok.is(tok::kw_requires))
2248  ParseTrailingRequiresClause(D);
2249  Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2250  D.complete(ThisDecl);
2251  if (ThisDecl)
2252  DeclsInGroup.push_back(ThisDecl);
2253  }
2254  }
2255 
2256  if (DeclEnd)
2257  *DeclEnd = Tok.getLocation();
2258 
2259  if (ExpectSemi && ExpectAndConsumeSemi(
2260  Context == DeclaratorContext::File
2261  ? diag::err_invalid_token_after_toplevel_declarator
2262  : diag::err_expected_semi_declaration)) {
2263  // Okay, there was no semicolon and one was expected. If we see a
2264  // declaration specifier, just assume it was missing and continue parsing.
2265  // Otherwise things are very confused and we skip to recover.
2266  if (!isDeclarationSpecifier(ImplicitTypenameContext::No)) {
2267  SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2268  TryConsumeToken(tok::semi);
2269  }
2270  }
2271 
2272  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2273 }
2274 
2275 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2276 /// declarator. Returns true on an error.
2277 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2278  // If a simple-asm-expr is present, parse it.
2279  if (Tok.is(tok::kw_asm)) {
2280  SourceLocation Loc;
2281  ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2282  if (AsmLabel.isInvalid()) {
2283  SkipUntil(tok::semi, StopBeforeMatch);
2284  return true;
2285  }
2286 
2287  D.setAsmLabel(AsmLabel.get());
2288  D.SetRangeEnd(Loc);
2289  }
2290 
2291  MaybeParseGNUAttributes(D);
2292  return false;
2293 }
2294 
2295 /// Parse 'declaration' after parsing 'declaration-specifiers
2296 /// declarator'. This method parses the remainder of the declaration
2297 /// (including any attributes or initializer, among other things) and
2298 /// finalizes the declaration.
2299 ///
2300 /// init-declarator: [C99 6.7]
2301 /// declarator
2302 /// declarator '=' initializer
2303 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2304 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2305 /// [C++] declarator initializer[opt]
2306 ///
2307 /// [C++] initializer:
2308 /// [C++] '=' initializer-clause
2309 /// [C++] '(' expression-list ')'
2310 /// [C++0x] '=' 'default' [TODO]
2311 /// [C++0x] '=' 'delete'
2312 /// [C++0x] braced-init-list
2313 ///
2314 /// According to the standard grammar, =default and =delete are function
2315 /// definitions, but that definitely doesn't fit with the parser here.
2316 ///
2317 Decl *Parser::ParseDeclarationAfterDeclarator(
2318  Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2319  if (ParseAsmAttributesAfterDeclarator(D))
2320  return nullptr;
2321 
2322  return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2323 }
2324 
2325 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2326  Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2327  // RAII type used to track whether we're inside an initializer.
2328  struct InitializerScopeRAII {
2329  Parser &P;
2330  Declarator &D;
2331  Decl *ThisDecl;
2332 
2333  InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2334  : P(P), D(D), ThisDecl(ThisDecl) {
2335  if (ThisDecl && P.getLangOpts().CPlusPlus) {
2336  Scope *S = nullptr;
2337  if (D.getCXXScopeSpec().isSet()) {
2338  P.EnterScope(0);
2339  S = P.getCurScope();
2340  }
2341  P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2342  }
2343  }
2344  ~InitializerScopeRAII() { pop(); }
2345  void pop() {
2346  if (ThisDecl && P.getLangOpts().CPlusPlus) {
2347  Scope *S = nullptr;
2348  if (D.getCXXScopeSpec().isSet())
2349  S = P.getCurScope();
2350  P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2351  if (S)
2352  P.ExitScope();
2353  }
2354  ThisDecl = nullptr;
2355  }
2356  };
2357 
2358  enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
2359  InitKind TheInitKind;
2360  // If a '==' or '+=' is found, suggest a fixit to '='.
2361  if (isTokenEqualOrEqualTypo())
2362  TheInitKind = InitKind::Equal;
2363  else if (Tok.is(tok::l_paren))
2364  TheInitKind = InitKind::CXXDirect;
2365  else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2366  (!CurParsedObjCImpl || !D.isFunctionDeclarator()))
2367  TheInitKind = InitKind::CXXBraced;
2368  else
2369  TheInitKind = InitKind::Uninitialized;
2370  if (TheInitKind != InitKind::Uninitialized)
2371  D.setHasInitializer();
2372 
2373  // Inform Sema that we just parsed this declarator.
2374  Decl *ThisDecl = nullptr;
2375  Decl *OuterDecl = nullptr;
2376  switch (TemplateInfo.Kind) {
2377  case ParsedTemplateInfo::NonTemplate:
2378  ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2379  break;
2380 
2381  case ParsedTemplateInfo::Template:
2382  case ParsedTemplateInfo::ExplicitSpecialization: {
2383  ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2384  *TemplateInfo.TemplateParams,
2385  D);
2386  if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2387  // Re-direct this decl to refer to the templated decl so that we can
2388  // initialize it.
2389  ThisDecl = VT->getTemplatedDecl();
2390  OuterDecl = VT;
2391  }
2392  break;
2393  }
2394  case ParsedTemplateInfo::ExplicitInstantiation: {
2395  if (Tok.is(tok::semi)) {
2396  DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2397  getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2398  if (ThisRes.isInvalid()) {
2399  SkipUntil(tok::semi, StopBeforeMatch);
2400  return nullptr;
2401  }
2402  ThisDecl = ThisRes.get();
2403  } else {
2404  // FIXME: This check should be for a variable template instantiation only.
2405 
2406  // Check that this is a valid instantiation
2408  // If the declarator-id is not a template-id, issue a diagnostic and
2409  // recover by ignoring the 'template' keyword.
2410  Diag(Tok, diag::err_template_defn_explicit_instantiation)
2411  << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2412  ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2413  } else {
2414  SourceLocation LAngleLoc =
2415  PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2416  Diag(D.getIdentifierLoc(),
2417  diag::err_explicit_instantiation_with_definition)
2418  << SourceRange(TemplateInfo.TemplateLoc)
2419  << FixItHint::CreateInsertion(LAngleLoc, "<>");
2420 
2421  // Recover as if it were an explicit specialization.
2422  TemplateParameterLists FakedParamLists;
2423  FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2424  0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2425  LAngleLoc, nullptr));
2426 
2427  ThisDecl =
2428  Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2429  }
2430  }
2431  break;
2432  }
2433  }
2434 
2435  switch (TheInitKind) {
2436  // Parse declarator '=' initializer.
2437  case InitKind::Equal: {
2438  SourceLocation EqualLoc = ConsumeToken();
2439 
2440  if (Tok.is(tok::kw_delete)) {
2441  if (D.isFunctionDeclarator())
2442  Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2443  << 1 /* delete */;
2444  else
2445  Diag(ConsumeToken(), diag::err_deleted_non_function);
2446  } else if (Tok.is(tok::kw_default)) {
2447  if (D.isFunctionDeclarator())
2448  Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2449  << 0 /* default */;
2450  else
2451  Diag(ConsumeToken(), diag::err_default_special_members)
2452  << getLangOpts().CPlusPlus20;
2453  } else {
2454  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2455 
2456  if (Tok.is(tok::code_completion)) {
2457  cutOffParsing();
2458  Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2459  Actions.FinalizeDeclaration(ThisDecl);
2460  return nullptr;
2461  }
2462 
2463  PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2464  ExprResult Init = ParseInitializer();
2465 
2466  // If this is the only decl in (possibly) range based for statement,
2467  // our best guess is that the user meant ':' instead of '='.
2468  if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2469  Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2470  << FixItHint::CreateReplacement(EqualLoc, ":");
2471  // We are trying to stop parser from looking for ';' in this for
2472  // statement, therefore preventing spurious errors to be issued.
2473  FRI->ColonLoc = EqualLoc;
2474  Init = ExprError();
2475  FRI->RangeExpr = Init;
2476  }
2477 
2478  InitScope.pop();
2479 
2480  if (Init.isInvalid()) {
2481  SmallVector<tok::TokenKind, 2> StopTokens;
2482  StopTokens.push_back(tok::comma);
2485  StopTokens.push_back(tok::r_paren);
2486  SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2487  Actions.ActOnInitializerError(ThisDecl);
2488  } else
2489  Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2490  /*DirectInit=*/false);
2491  }
2492  break;
2493  }
2494  case InitKind::CXXDirect: {
2495  // Parse C++ direct initializer: '(' expression-list ')'
2496  BalancedDelimiterTracker T(*this, tok::l_paren);
2497  T.consumeOpen();
2498 
2499  ExprVector Exprs;
2500 
2501  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2502 
2503  auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2504  auto RunSignatureHelp = [&]() {
2505  QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2506  ThisVarDecl->getType()->getCanonicalTypeInternal(),
2507  ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2508  /*Braced=*/false);
2509  CalledSignatureHelp = true;
2510  return PreferredType;
2511  };
2512  auto SetPreferredType = [&] {
2513  PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2514  };
2515 
2516  llvm::function_ref<void()> ExpressionStarts;
2517  if (ThisVarDecl) {
2518  // ParseExpressionList can sometimes succeed even when ThisDecl is not
2519  // VarDecl. This is an error and it is reported in a call to
2520  // Actions.ActOnInitializerError(). However, we call
2521  // ProduceConstructorSignatureHelp only on VarDecls.
2522  ExpressionStarts = SetPreferredType;
2523  }
2524  if (ParseExpressionList(Exprs, ExpressionStarts)) {
2525  if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2527  ThisVarDecl->getType()->getCanonicalTypeInternal(),
2528  ThisDecl->getLocation(), Exprs, T.getOpenLocation(),
2529  /*Braced=*/false);
2530  CalledSignatureHelp = true;
2531  }
2532  Actions.ActOnInitializerError(ThisDecl);
2533  SkipUntil(tok::r_paren, StopAtSemi);
2534  } else {
2535  // Match the ')'.
2536  T.consumeClose();
2537  InitScope.pop();
2538 
2539  ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2540  T.getCloseLocation(),
2541  Exprs);
2542  Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2543  /*DirectInit=*/true);
2544  }
2545  break;
2546  }
2547  case InitKind::CXXBraced: {
2548  // Parse C++0x braced-init-list.
2549  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2550 
2551  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2552 
2553  PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2554  ExprResult Init(ParseBraceInitializer());
2555 
2556  InitScope.pop();
2557 
2558  if (Init.isInvalid()) {
2559  Actions.ActOnInitializerError(ThisDecl);
2560  } else
2561  Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2562  break;
2563  }
2564  case InitKind::Uninitialized: {
2565  Actions.ActOnUninitializedDecl(ThisDecl);
2566  break;
2567  }
2568  }
2569 
2570  Actions.FinalizeDeclaration(ThisDecl);
2571  return OuterDecl ? OuterDecl : ThisDecl;
2572 }
2573 
2574 /// ParseSpecifierQualifierList
2575 /// specifier-qualifier-list:
2576 /// type-specifier specifier-qualifier-list[opt]
2577 /// type-qualifier specifier-qualifier-list[opt]
2578 /// [GNU] attributes specifier-qualifier-list[opt]
2579 ///
2580 void Parser::ParseSpecifierQualifierList(
2581  DeclSpec &DS, ImplicitTypenameContext AllowImplicitTypename,
2582  AccessSpecifier AS, DeclSpecContext DSC) {
2583  /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2584  /// parse declaration-specifiers and complain about extra stuff.
2585  /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2586  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC, nullptr,
2587  AllowImplicitTypename);
2588 
2589  // Validate declspec for type-name.
2590  unsigned Specs = DS.getParsedSpecifiers();
2591  if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2592  Diag(Tok, diag::err_expected_type);
2593  DS.SetTypeSpecError();
2594  } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2595  Diag(Tok, diag::err_typename_requires_specqual);
2596  if (!DS.hasTypeSpecifier())
2597  DS.SetTypeSpecError();
2598  }
2599 
2600  // Issue diagnostic and remove storage class if present.
2601  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2602  if (DS.getStorageClassSpecLoc().isValid())
2603  Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2604  else
2606  diag::err_typename_invalid_storageclass);
2608  }
2609 
2610  // Issue diagnostic and remove function specifier if present.
2611  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2612  if (DS.isInlineSpecified())
2613  Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2614  if (DS.isVirtualSpecified())
2615  Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2616  if (DS.hasExplicitSpecifier())
2617  Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2618  if (DS.isNoreturnSpecified())
2619  Diag(DS.getNoreturnSpecLoc(), diag::err_typename_invalid_functionspec);
2620  DS.ClearFunctionSpecs();
2621  }
2622 
2623  // Issue diagnostic and remove constexpr specifier if present.
2624  if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2625  Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2626  << static_cast<int>(DS.getConstexprSpecifier());
2627  DS.ClearConstexprSpec();
2628  }
2629 }
2630 
2631 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2632 /// specified token is valid after the identifier in a declarator which
2633 /// immediately follows the declspec. For example, these things are valid:
2634 ///
2635 /// int x [ 4]; // direct-declarator
2636 /// int x ( int y); // direct-declarator
2637 /// int(int x ) // direct-declarator
2638 /// int x ; // simple-declaration
2639 /// int x = 17; // init-declarator-list
2640 /// int x , y; // init-declarator-list
2641 /// int x __asm__ ("foo"); // init-declarator-list
2642 /// int x : 4; // struct-declarator
2643 /// int x { 5}; // C++'0x unified initializers
2644 ///
2645 /// This is not, because 'x' does not immediately follow the declspec (though
2646 /// ')' happens to be valid anyway).
2647 /// int (x)
2648 ///
2650  return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2651  tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2652  tok::colon);
2653 }
2654 
2655 /// ParseImplicitInt - This method is called when we have an non-typename
2656 /// identifier in a declspec (which normally terminates the decl spec) when
2657 /// the declspec has no type specifier. In this case, the declspec is either
2658 /// malformed or is "implicit int" (in K&R and C89).
2659 ///
2660 /// This method handles diagnosing this prettily and returns false if the
2661 /// declspec is done being processed. If it recovers and thinks there may be
2662 /// other pieces of declspec after it, it returns true.
2663 ///
2664 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2665  const ParsedTemplateInfo &TemplateInfo,
2666  AccessSpecifier AS, DeclSpecContext DSC,
2667  ParsedAttributes &Attrs) {
2668  assert(Tok.is(tok::identifier) && "should have identifier");
2669 
2670  SourceLocation Loc = Tok.getLocation();
2671  // If we see an identifier that is not a type name, we normally would
2672  // parse it as the identifier being declared. However, when a typename
2673  // is typo'd or the definition is not included, this will incorrectly
2674  // parse the typename as the identifier name and fall over misparsing
2675  // later parts of the diagnostic.
2676  //
2677  // As such, we try to do some look-ahead in cases where this would
2678  // otherwise be an "implicit-int" case to see if this is invalid. For
2679  // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2680  // an identifier with implicit int, we'd get a parse error because the
2681  // next token is obviously invalid for a type. Parse these as a case
2682  // with an invalid type specifier.
2683  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2684 
2685  // Since we know that this either implicit int (which is rare) or an
2686  // error, do lookahead to try to do better recovery. This never applies
2687  // within a type specifier. Outside of C++, we allow this even if the
2688  // language doesn't "officially" support implicit int -- we support
2689  // implicit int as an extension in some language modes.
2690  if (!isTypeSpecifier(DSC) && getLangOpts().isImplicitIntAllowed() &&
2692  // If this token is valid for implicit int, e.g. "static x = 4", then
2693  // we just avoid eating the identifier, so it will be parsed as the
2694  // identifier in the declarator.
2695  return false;
2696  }
2697 
2698  // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2699  // for incomplete declarations such as `pipe p`.
2700  if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2701  return false;
2702 
2703  if (getLangOpts().CPlusPlus &&
2705  // Don't require a type specifier if we have the 'auto' storage class
2706  // specifier in C++98 -- we'll promote it to a type specifier.
2707  if (SS)
2708  AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2709  return false;
2710  }
2711 
2712  if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2713  getLangOpts().MSVCCompat) {
2714  // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2715  // Give Sema a chance to recover if we are in a template with dependent base
2716  // classes.
2717  if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2718  *Tok.getIdentifierInfo(), Tok.getLocation(),
2719  DSC == DeclSpecContext::DSC_template_type_arg)) {
2720  const char *PrevSpec;
2721  unsigned DiagID;
2722  DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2723  Actions.getASTContext().getPrintingPolicy());
2724  DS.SetRangeEnd(Tok.getLocation());
2725  ConsumeToken();
2726  return false;
2727  }
2728  }
2729 
2730  // Otherwise, if we don't consume this token, we are going to emit an
2731  // error anyway. Try to recover from various common problems. Check
2732  // to see if this was a reference to a tag name without a tag specified.
2733  // This is a common problem in C (saying 'foo' instead of 'struct foo').
2734  //
2735  // C++ doesn't need this, and isTagName doesn't take SS.
2736  if (SS == nullptr) {
2737  const char *TagName = nullptr, *FixitTagName = nullptr;
2738  tok::TokenKind TagKind = tok::unknown;
2739 
2740  switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2741  default: break;
2742  case DeclSpec::TST_enum:
2743  TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2744  case DeclSpec::TST_union:
2745  TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2746  case DeclSpec::TST_struct:
2747  TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2749  TagName="__interface"; FixitTagName = "__interface ";
2750  TagKind=tok::kw___interface;break;
2751  case DeclSpec::TST_class:
2752  TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2753  }
2754 
2755  if (TagName) {
2756  IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2757  LookupResult R(Actions, TokenName, SourceLocation(),
2759 
2760  Diag(Loc, diag::err_use_of_tag_name_without_tag)
2761  << TokenName << TagName << getLangOpts().CPlusPlus
2762  << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2763 
2764  if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2765  for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2766  I != IEnd; ++I)
2767  Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2768  << TokenName << TagName;
2769  }
2770 
2771  // Parse this as a tag as if the missing tag were present.
2772  if (TagKind == tok::kw_enum)
2773  ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2774  DeclSpecContext::DSC_normal);
2775  else
2776  ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2777  /*EnteringContext*/ false,
2778  DeclSpecContext::DSC_normal, Attrs);
2779  return true;
2780  }
2781  }
2782 
2783  // Determine whether this identifier could plausibly be the name of something
2784  // being declared (with a missing type).
2785  if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2786  DSC == DeclSpecContext::DSC_class)) {
2787  // Look ahead to the next token to try to figure out what this declaration
2788  // was supposed to be.
2789  switch (NextToken().getKind()) {
2790  case tok::l_paren: {
2791  // static x(4); // 'x' is not a type
2792  // x(int n); // 'x' is not a type
2793  // x (*p)[]; // 'x' is a type
2794  //
2795  // Since we're in an error case, we can afford to perform a tentative
2796  // parse to determine which case we're in.
2797  TentativeParsingAction PA(*this);
2798  ConsumeToken();
2799  TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2800  PA.Revert();
2801 
2802  if (TPR != TPResult::False) {
2803  // The identifier is followed by a parenthesized declarator.
2804  // It's supposed to be a type.
2805  break;
2806  }
2807 
2808  // If we're in a context where we could be declaring a constructor,
2809  // check whether this is a constructor declaration with a bogus name.
2810  if (DSC == DeclSpecContext::DSC_class ||
2811  (DSC == DeclSpecContext::DSC_top_level && SS)) {
2812  IdentifierInfo *II = Tok.getIdentifierInfo();
2813  if (Actions.isCurrentClassNameTypo(II, SS)) {
2814  Diag(Loc, diag::err_constructor_bad_name)
2815  << Tok.getIdentifierInfo() << II
2817  Tok.setIdentifierInfo(II);
2818  }
2819  }
2820  // Fall through.
2821  [[fallthrough]];
2822  }
2823  case tok::comma:
2824  case tok::equal:
2825  case tok::kw_asm:
2826  case tok::l_brace:
2827  case tok::l_square:
2828  case tok::semi:
2829  // This looks like a variable or function declaration. The type is
2830  // probably missing. We're done parsing decl-specifiers.
2831  // But only if we are not in a function prototype scope.
2832  if (getCurScope()->isFunctionPrototypeScope())
2833  break;
2834  if (SS)
2835  AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2836  return false;
2837 
2838  default:
2839  // This is probably supposed to be a type. This includes cases like:
2840  // int f(itn);
2841  // struct S { unsigned : 4; };
2842  break;
2843  }
2844  }
2845 
2846  // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2847  // and attempt to recover.
2848  ParsedType T;
2849  IdentifierInfo *II = Tok.getIdentifierInfo();
2850  bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2851  Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2852  IsTemplateName);
2853  if (T) {
2854  // The action has suggested that the type T could be used. Set that as
2855  // the type in the declaration specifiers, consume the would-be type
2856  // name token, and we're done.
2857  const char *PrevSpec;
2858  unsigned DiagID;
2859  DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2860  Actions.getASTContext().getPrintingPolicy());
2861  DS.SetRangeEnd(Tok.getLocation());
2862  ConsumeToken();
2863  // There may be other declaration specifiers after this.
2864  return true;
2865  } else if (II != Tok.getIdentifierInfo()) {
2866  // If no type was suggested, the correction is to a keyword
2867  Tok.setKind(II->getTokenID());
2868  // There may be other declaration specifiers after this.
2869  return true;
2870  }
2871 
2872  // Otherwise, the action had no suggestion for us. Mark this as an error.
2873  DS.SetTypeSpecError();
2874  DS.SetRangeEnd(Tok.getLocation());
2875  ConsumeToken();
2876 
2877  // Eat any following template arguments.
2878  if (IsTemplateName) {
2879  SourceLocation LAngle, RAngle;
2880  TemplateArgList Args;
2881  ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2882  }
2883 
2884  // TODO: Could inject an invalid typedef decl in an enclosing scope to
2885  // avoid rippling error messages on subsequent uses of the same type,
2886  // could be useful if #include was forgotten.
2887  return true;
2888 }
2889 
2890 /// Determine the declaration specifier context from the declarator
2891 /// context.
2892 ///
2893 /// \param Context the declarator context, which is one of the
2894 /// DeclaratorContext enumerator values.
2895 Parser::DeclSpecContext
2896 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2897  switch (Context) {
2899  return DeclSpecContext::DSC_class;
2901  return DeclSpecContext::DSC_top_level;
2903  return DeclSpecContext::DSC_template_param;
2905  return DeclSpecContext::DSC_template_arg;
2907  return DeclSpecContext::DSC_template_type_arg;
2910  return DeclSpecContext::DSC_trailing;
2913  return DeclSpecContext::DSC_alias_declaration;
2915  return DeclSpecContext::DSC_association;
2917  return DeclSpecContext::DSC_type_specifier;
2919  return DeclSpecContext::DSC_condition;
2921  return DeclSpecContext::DSC_conv_operator;
2937  return DeclSpecContext::DSC_normal;
2938  }
2939 
2940  llvm_unreachable("Missing DeclaratorContext case");
2941 }
2942 
2943 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2944 ///
2945 /// FIXME: Simply returns an alignof() expression if the argument is a
2946 /// type. Ideally, the type should be propagated directly into Sema.
2947 ///
2948 /// [C11] type-id
2949 /// [C11] constant-expression
2950 /// [C++0x] type-id ...[opt]
2951 /// [C++0x] assignment-expression ...[opt]
2952 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2953  SourceLocation &EllipsisLoc) {
2954  ExprResult ER;
2955  if (isTypeIdInParens()) {
2957  ParsedType Ty = ParseTypeName().get();
2958  SourceRange TypeRange(Start, Tok.getLocation());
2959  ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2960  Ty.getAsOpaquePtr(), TypeRange);
2961  } else
2962  ER = ParseConstantExpression();
2963 
2964  if (getLangOpts().CPlusPlus11)
2965  TryConsumeToken(tok::ellipsis, EllipsisLoc);
2966 
2967  return ER;
2968 }
2969 
2970 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2971 /// attribute to Attrs.
2972 ///
2973 /// alignment-specifier:
2974 /// [C11] '_Alignas' '(' type-id ')'
2975 /// [C11] '_Alignas' '(' constant-expression ')'
2976 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2977 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2978 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2979  SourceLocation *EndLoc) {
2980  assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2981  "Not an alignment-specifier!");
2982 
2983  IdentifierInfo *KWName = Tok.getIdentifierInfo();
2984  SourceLocation KWLoc = ConsumeToken();
2985 
2986  BalancedDelimiterTracker T(*this, tok::l_paren);
2987  if (T.expectAndConsume())
2988  return;
2989 
2990  SourceLocation EllipsisLoc;
2991  ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2992  if (ArgExpr.isInvalid()) {
2993  T.skipToEnd();
2994  return;
2995  }
2996 
2997  T.consumeClose();
2998  if (EndLoc)
2999  *EndLoc = T.getCloseLocation();
3000 
3001  ArgsVector ArgExprs;
3002  ArgExprs.push_back(ArgExpr.get());
3003  Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
3004  ParsedAttr::AS_Keyword, EllipsisLoc);
3005 }
3006 
3007 ExprResult Parser::ParseExtIntegerArgument() {
3008  assert(Tok.isOneOf(tok::kw__ExtInt, tok::kw__BitInt) &&
3009  "Not an extended int type");
3010  ConsumeToken();
3011 
3012  BalancedDelimiterTracker T(*this, tok::l_paren);
3013  if (T.expectAndConsume())
3014  return ExprError();
3015 
3017  if (ER.isInvalid()) {
3018  T.skipToEnd();
3019  return ExprError();
3020  }
3021 
3022  if(T.consumeClose())
3023  return ExprError();
3024  return ER;
3025 }
3026 
3027 /// Determine whether we're looking at something that might be a declarator
3028 /// in a simple-declaration. If it can't possibly be a declarator, maybe
3029 /// diagnose a missing semicolon after a prior tag definition in the decl
3030 /// specifier.
3031 ///
3032 /// \return \c true if an error occurred and this can't be any kind of
3033 /// declaration.
3034 bool
3035 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
3036  DeclSpecContext DSContext,
3037  LateParsedAttrList *LateAttrs) {
3038  assert(DS.hasTagDefinition() && "shouldn't call this");
3039 
3040  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3041  DSContext == DeclSpecContext::DSC_top_level);
3042 
3043  if (getLangOpts().CPlusPlus &&
3044  Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
3045  tok::annot_template_id) &&
3046  TryAnnotateCXXScopeToken(EnteringContext)) {
3048  return true;
3049  }
3050 
3051  bool HasScope = Tok.is(tok::annot_cxxscope);
3052  // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
3053  Token AfterScope = HasScope ? NextToken() : Tok;
3054 
3055  // Determine whether the following tokens could possibly be a
3056  // declarator.
3057  bool MightBeDeclarator = true;
3058  if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
3059  // A declarator-id can't start with 'typename'.
3060  MightBeDeclarator = false;
3061  } else if (AfterScope.is(tok::annot_template_id)) {
3062  // If we have a type expressed as a template-id, this cannot be a
3063  // declarator-id (such a type cannot be redeclared in a simple-declaration).
3064  TemplateIdAnnotation *Annot =
3065  static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
3066  if (Annot->Kind == TNK_Type_template)
3067  MightBeDeclarator = false;
3068  } else if (AfterScope.is(tok::identifier)) {
3069  const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
3070 
3071  // These tokens cannot come after the declarator-id in a
3072  // simple-declaration, and are likely to come after a type-specifier.
3073  if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
3074  tok::annot_cxxscope, tok::coloncolon)) {
3075  // Missing a semicolon.
3076  MightBeDeclarator = false;
3077  } else if (HasScope) {
3078  // If the declarator-id has a scope specifier, it must redeclare a
3079  // previously-declared entity. If that's a type (and this is not a
3080  // typedef), that's an error.
3081  CXXScopeSpec SS;
3083  Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3084  IdentifierInfo *Name = AfterScope.getIdentifierInfo();
3085  Sema::NameClassification Classification = Actions.ClassifyName(
3086  getCurScope(), SS, Name, AfterScope.getLocation(), Next,
3087  /*CCC=*/nullptr);
3088  switch (Classification.getKind()) {
3089  case Sema::NC_Error:
3091  return true;
3092 
3093  case Sema::NC_Keyword:
3094  llvm_unreachable("typo correction is not possible here");
3095 
3096  case Sema::NC_Type:
3097  case Sema::NC_TypeTemplate:
3100  // Not a previously-declared non-type entity.
3101  MightBeDeclarator = false;
3102  break;
3103 
3104  case Sema::NC_Unknown:
3105  case Sema::NC_NonType:
3107  case Sema::NC_OverloadSet:
3108  case Sema::NC_VarTemplate:
3110  case Sema::NC_Concept:
3111  // Might be a redeclaration of a prior entity.
3112  break;
3113  }
3114  }
3115  }
3116 
3117  if (MightBeDeclarator)
3118  return false;
3119 
3120  const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
3122  diag::err_expected_after)
3123  << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
3124 
3125  // Try to recover from the typo, by dropping the tag definition and parsing
3126  // the problematic tokens as a type.
3127  //
3128  // FIXME: Split the DeclSpec into pieces for the standalone
3129  // declaration and pieces for the following declaration, instead
3130  // of assuming that all the other pieces attach to new declaration,
3131  // and call ParsedFreeStandingDeclSpec as appropriate.
3132  DS.ClearTypeSpecType();
3133  ParsedTemplateInfo NotATemplate;
3134  ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
3135  return false;
3136 }
3137 
3138 // Choose the apprpriate diagnostic error for why fixed point types are
3139 // disabled, set the previous specifier, and mark as invalid.
3140 static void SetupFixedPointError(const LangOptions &LangOpts,
3141  const char *&PrevSpec, unsigned &DiagID,
3142  bool &isInvalid) {
3143  assert(!LangOpts.FixedPoint);
3144  DiagID = diag::err_fixed_point_not_enabled;
3145  PrevSpec = ""; // Not used by diagnostic
3146  isInvalid = true;
3147 }
3148 
3149 /// ParseDeclarationSpecifiers
3150 /// declaration-specifiers: [C99 6.7]
3151 /// storage-class-specifier declaration-specifiers[opt]
3152 /// type-specifier declaration-specifiers[opt]
3153 /// [C99] function-specifier declaration-specifiers[opt]
3154 /// [C11] alignment-specifier declaration-specifiers[opt]
3155 /// [GNU] attributes declaration-specifiers[opt]
3156 /// [Clang] '__module_private__' declaration-specifiers[opt]
3157 /// [ObjC1] '__kindof' declaration-specifiers[opt]
3158 ///
3159 /// storage-class-specifier: [C99 6.7.1]
3160 /// 'typedef'
3161 /// 'extern'
3162 /// 'static'
3163 /// 'auto'
3164 /// 'register'
3165 /// [C++] 'mutable'
3166 /// [C++11] 'thread_local'
3167 /// [C11] '_Thread_local'
3168 /// [GNU] '__thread'
3169 /// function-specifier: [C99 6.7.4]
3170 /// [C99] 'inline'
3171 /// [C++] 'virtual'
3172 /// [C++] 'explicit'
3173 /// [OpenCL] '__kernel'
3174 /// 'friend': [C++ dcl.friend]
3175 /// 'constexpr': [C++0x dcl.constexpr]
3176 void Parser::ParseDeclarationSpecifiers(
3177  DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
3178  DeclSpecContext DSContext, LateParsedAttrList *LateAttrs,
3179  ImplicitTypenameContext AllowImplicitTypename) {
3180  if (DS.getSourceRange().isInvalid()) {
3181  // Start the range at the current token but make the end of the range
3182  // invalid. This will make the entire range invalid unless we successfully
3183  // consume a token.
3184  DS.SetRangeStart(Tok.getLocation());
3186  }
3187 
3188  // If we are in a operator context, convert it back into a type specifier
3189  // context for better error handling later on.
3190  if (DSContext == DeclSpecContext::DSC_conv_operator) {
3191  // No implicit typename here.
3192  AllowImplicitTypename = ImplicitTypenameContext::No;
3193  DSContext = DeclSpecContext::DSC_type_specifier;
3194  }
3195 
3196  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3197  DSContext == DeclSpecContext::DSC_top_level);
3198  bool AttrsLastTime = false;
3199  ParsedAttributes attrs(AttrFactory);
3200  // We use Sema's policy to get bool macros right.
3202  while (true) {
3203  bool isInvalid = false;
3204  bool isStorageClass = false;
3205  const char *PrevSpec = nullptr;
3206  unsigned DiagID = 0;
3207 
3208  // This value needs to be set to the location of the last token if the last
3209  // token of the specifier is already consumed.
3210  SourceLocation ConsumedEnd;
3211 
3212  // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3213  // implementation for VS2013 uses _Atomic as an identifier for one of the
3214  // classes in <atomic>.
3215  //
3216  // A typedef declaration containing _Atomic<...> is among the places where
3217  // the class is used. If we are currently parsing such a declaration, treat
3218  // the token as an identifier.
3219  if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3221  !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3222  Tok.setKind(tok::identifier);
3223 
3224  SourceLocation Loc = Tok.getLocation();
3225 
3226  // Helper for image types in OpenCL.
3227  auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
3228  // Check if the image type is supported and otherwise turn the keyword into an identifier
3229  // because image types from extensions are not reserved identifiers.
3230  if (!StringRef(Ext).empty() && !getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())) {
3232  Tok.setKind(tok::identifier);
3233  return false;
3234  }
3235  isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3236  return true;
3237  };
3238 
3239  // Turn off usual access checking for template specializations and
3240  // instantiations.
3241  bool IsTemplateSpecOrInst =
3242  (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3243  TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
3244 
3245  switch (Tok.getKind()) {
3246  default:
3247  DoneWithDeclSpec:
3248  if (!AttrsLastTime)
3249  ProhibitAttributes(attrs);
3250  else {
3251  // Reject C++11 / C2x attributes that aren't type attributes.
3252  for (const ParsedAttr &PA : attrs) {
3253  if (!PA.isCXX11Attribute() && !PA.isC2xAttribute())
3254  continue;
3255  if (PA.getKind() == ParsedAttr::UnknownAttribute)
3256  // We will warn about the unknown attribute elsewhere (in
3257  // SemaDeclAttr.cpp)
3258  continue;
3259  // GCC ignores this attribute when placed on the DeclSpec in [[]]
3260  // syntax, so we do the same.
3261  if (PA.getKind() == ParsedAttr::AT_VectorSize) {
3262  Diag(PA.getLoc(), diag::warn_attribute_ignored) << PA;
3263  PA.setInvalid();
3264  continue;
3265  }
3266  // We reject AT_LifetimeBound and AT_AnyX86NoCfCheck, even though they
3267  // are type attributes, because we historically haven't allowed these
3268  // to be used as type attributes in C++11 / C2x syntax.
3269  if (PA.isTypeAttr() && PA.getKind() != ParsedAttr::AT_LifetimeBound &&
3270  PA.getKind() != ParsedAttr::AT_AnyX86NoCfCheck)
3271  continue;
3272  Diag(PA.getLoc(), diag::err_attribute_not_type_attr) << PA;
3273  PA.setInvalid();
3274  }
3275 
3276  DS.takeAttributesFrom(attrs);
3277  }
3278 
3279  // If this is not a declaration specifier token, we're done reading decl
3280  // specifiers. First verify that DeclSpec's are consistent.
3281  DS.Finish(Actions, Policy);
3282  return;
3283 
3284  case tok::l_square:
3285  case tok::kw_alignas:
3286  if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3287  goto DoneWithDeclSpec;
3288 
3289  ProhibitAttributes(attrs);
3290  // FIXME: It would be good to recover by accepting the attributes,
3291  // but attempting to do that now would cause serious
3292  // madness in terms of diagnostics.
3293  attrs.clear();
3294  attrs.Range = SourceRange();
3295 
3296  ParseCXX11Attributes(attrs);
3297  AttrsLastTime = true;
3298  continue;
3299 
3300  case tok::code_completion: {
3302  if (DS.hasTypeSpecifier()) {
3303  bool AllowNonIdentifiers
3308  Scope::AtCatchScope)) == 0;
3309  bool AllowNestedNameSpecifiers
3310  = DSContext == DeclSpecContext::DSC_top_level ||
3311  (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3312 
3313  cutOffParsing();
3314  Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3315  AllowNonIdentifiers,
3316  AllowNestedNameSpecifiers);
3317  return;
3318  }
3319 
3320  // Class context can appear inside a function/block, so prioritise that.
3321  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3322  CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3324  else if (DSContext == DeclSpecContext::DSC_class)
3325  CCC = Sema::PCC_Class;
3326  else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3328  else if (CurParsedObjCImpl)
3330 
3331  cutOffParsing();
3332  Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3333  return;
3334  }
3335 
3336  case tok::coloncolon: // ::foo::bar
3337  // C++ scope specifier. Annotate and loop, or bail out on error.
3338  if (TryAnnotateCXXScopeToken(EnteringContext)) {
3339  if (!DS.hasTypeSpecifier())
3340  DS.SetTypeSpecError();
3341  goto DoneWithDeclSpec;
3342  }
3343  if (Tok.is(tok::coloncolon)) // ::new or ::delete
3344  goto DoneWithDeclSpec;
3345  continue;
3346 
3347  case tok::annot_cxxscope: {
3348  if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3349  goto DoneWithDeclSpec;
3350 
3351  CXXScopeSpec SS;
3353  Tok.getAnnotationRange(),
3354  SS);
3355 
3356  // We are looking for a qualified typename.
3357  Token Next = NextToken();
3358 
3359  TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3360  ? takeTemplateIdAnnotation(Next)
3361  : nullptr;
3362  if (TemplateId && TemplateId->hasInvalidName()) {
3363  // We found something like 'T::U<Args> x', but U is not a template.
3364  // Assume it was supposed to be a type.
3365  DS.SetTypeSpecError();
3366  ConsumeAnnotationToken();
3367  break;
3368  }
3369 
3370  if (TemplateId && TemplateId->Kind == TNK_Type_template) {
3371  // We have a qualified template-id, e.g., N::A<int>
3372 
3373  // If this would be a valid constructor declaration with template
3374  // arguments, we will reject the attempt to form an invalid type-id
3375  // referring to the injected-class-name when we annotate the token,
3376  // per C++ [class.qual]p2.
3377  //
3378  // To improve diagnostics for this case, parse the declaration as a
3379  // constructor (and reject the extra template arguments later).
3380  if ((DSContext == DeclSpecContext::DSC_top_level ||
3381  DSContext == DeclSpecContext::DSC_class) &&
3382  TemplateId->Name &&
3383  Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3384  isConstructorDeclarator(/*Unqualified=*/false,
3385  /*DeductionGuide=*/false,
3386  DS.isFriendSpecified())) {
3387  // The user meant this to be an out-of-line constructor
3388  // definition, but template arguments are not allowed
3389  // there. Just allow this as a constructor; we'll
3390  // complain about it later.
3391  goto DoneWithDeclSpec;
3392  }
3393 
3394  DS.getTypeSpecScope() = SS;
3395  ConsumeAnnotationToken(); // The C++ scope.
3396  assert(Tok.is(tok::annot_template_id) &&
3397  "ParseOptionalCXXScopeSpecifier not working");
3398  AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3399  continue;
3400  }
3401 
3402  if (TemplateId && TemplateId->Kind == TNK_Concept_template &&
3403  GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype)) {
3404  DS.getTypeSpecScope() = SS;
3405  // This is a qualified placeholder-specifier, e.g., ::C<int> auto ...
3406  // Consume the scope annotation and continue to consume the template-id
3407  // as a placeholder-specifier.
3408  ConsumeAnnotationToken();
3409  continue;
3410  }
3411 
3412  if (Next.is(tok::annot_typename)) {
3413  DS.getTypeSpecScope() = SS;
3414  ConsumeAnnotationToken(); // The C++ scope.
3415  TypeResult T = getTypeAnnotation(Tok);
3417  Tok.getAnnotationEndLoc(),
3418  PrevSpec, DiagID, T, Policy);
3419  if (isInvalid)
3420  break;
3421  DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3422  ConsumeAnnotationToken(); // The typename
3423  }
3424 
3425  if (AllowImplicitTypename == ImplicitTypenameContext::Yes &&
3426  Next.is(tok::annot_template_id) &&
3427  static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3429  DS.getTypeSpecScope() = SS;
3430  ConsumeAnnotationToken(); // The C++ scope.
3431  AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3432  continue;
3433  }
3434 
3435  if (Next.isNot(tok::identifier))
3436  goto DoneWithDeclSpec;
3437 
3438  // Check whether this is a constructor declaration. If we're in a
3439  // context where the identifier could be a class name, and it has the
3440  // shape of a constructor declaration, process it as one.
3441  if ((DSContext == DeclSpecContext::DSC_top_level ||
3442  DSContext == DeclSpecContext::DSC_class) &&
3443  Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3444  &SS) &&
3445  isConstructorDeclarator(/*Unqualified=*/false,
3446  /*DeductionGuide=*/false,
3447  DS.isFriendSpecified()))
3448  goto DoneWithDeclSpec;
3449 
3450  // C++20 [temp.spec] 13.9/6.
3451  // This disables the access checking rules for function template explicit
3452  // instantiation and explicit specialization:
3453  // - `return type`.
3454  SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3455 
3456  ParsedType TypeRep = Actions.getTypeName(
3457  *Next.getIdentifierInfo(), Next.getLocation(), getCurScope(), &SS,
3458  false, false, nullptr,
3459  /*IsCtorOrDtorName=*/false,
3460  /*WantNontrivialTypeSourceInfo=*/true,
3461  isClassTemplateDeductionContext(DSContext), AllowImplicitTypename);
3462 
3463  if (IsTemplateSpecOrInst)
3464  SAC.done();
3465 
3466  // If the referenced identifier is not a type, then this declspec is
3467  // erroneous: We already checked about that it has no type specifier, and
3468  // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3469  // typename.
3470  if (!TypeRep) {
3471  if (TryAnnotateTypeConstraint())
3472  goto DoneWithDeclSpec;
3473  if (Tok.isNot(tok::annot_cxxscope) ||
3474  NextToken().isNot(tok::identifier))
3475  continue;
3476  // Eat the scope spec so the identifier is current.
3477  ConsumeAnnotationToken();
3478  ParsedAttributes Attrs(AttrFactory);
3479  if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3480  if (!Attrs.empty()) {
3481  AttrsLastTime = true;
3482  attrs.takeAllFrom(Attrs);
3483  }
3484  continue;
3485  }
3486  goto DoneWithDeclSpec;
3487  }
3488 
3489  DS.getTypeSpecScope() = SS;
3490  ConsumeAnnotationToken(); // The C++ scope.
3491 
3492  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3493  DiagID, TypeRep, Policy);
3494  if (isInvalid)
3495  break;
3496 
3497  DS.SetRangeEnd(Tok.getLocation());
3498  ConsumeToken(); // The typename.
3499 
3500  continue;
3501  }
3502 
3503  case tok::annot_typename: {
3504  // If we've previously seen a tag definition, we were almost surely
3505  // missing a semicolon after it.
3506  if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3507  goto DoneWithDeclSpec;
3508 
3509  TypeResult T = getTypeAnnotation(Tok);
3510  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3511  DiagID, T, Policy);
3512  if (isInvalid)
3513  break;
3514 
3515  DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3516  ConsumeAnnotationToken(); // The typename
3517 
3518  continue;
3519  }
3520 
3521  case tok::kw___is_signed:
3522  // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3523  // typically treats it as a trait. If we see __is_signed as it appears
3524  // in libstdc++, e.g.,
3525  //
3526  // static const bool __is_signed;
3527  //
3528  // then treat __is_signed as an identifier rather than as a keyword.
3529  if (DS.getTypeSpecType() == TST_bool &&
3532  TryKeywordIdentFallback(true);
3533 
3534  // We're done with the declaration-specifiers.
3535  goto DoneWithDeclSpec;
3536 
3537  // typedef-name
3538  case tok::kw___super:
3539  case tok::kw_decltype:
3540  case tok::identifier:
3541  ParseIdentifier: {
3542  // This identifier can only be a typedef name if we haven't already seen
3543  // a type-specifier. Without this check we misparse:
3544  // typedef int X; struct Y { short X; }; as 'short int'.
3545  if (DS.hasTypeSpecifier())
3546  goto DoneWithDeclSpec;
3547 
3548  // If the token is an identifier named "__declspec" and Microsoft
3549  // extensions are not enabled, it is likely that there will be cascading
3550  // parse errors if this really is a __declspec attribute. Attempt to
3551  // recognize that scenario and recover gracefully.
3552  if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3553  Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3554  Diag(Loc, diag::err_ms_attributes_not_enabled);
3555 
3556  // The next token should be an open paren. If it is, eat the entire
3557  // attribute declaration and continue.
3558  if (NextToken().is(tok::l_paren)) {
3559  // Consume the __declspec identifier.
3560  ConsumeToken();
3561 
3562  // Eat the parens and everything between them.
3563  BalancedDelimiterTracker T(*this, tok::l_paren);
3564  if (T.consumeOpen()) {
3565  assert(false && "Not a left paren?");
3566  return;
3567  }
3568  T.skipToEnd();
3569  continue;
3570  }
3571  }
3572 
3573  // In C++, check to see if this is a scope specifier like foo::bar::, if
3574  // so handle it as such. This is important for ctor parsing.
3575  if (getLangOpts().CPlusPlus) {
3576  // C++20 [temp.spec] 13.9/6.
3577  // This disables the access checking rules for function template
3578  // explicit instantiation and explicit specialization:
3579  // - `return type`.
3580  SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3581 
3582  const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
3583 
3584  if (IsTemplateSpecOrInst)
3585  SAC.done();
3586 
3587  if (Success) {
3588  if (IsTemplateSpecOrInst)
3589  SAC.redelay();
3590  DS.SetTypeSpecError();
3591  goto DoneWithDeclSpec;
3592  }
3593 
3594  if (!Tok.is(tok::identifier))
3595  continue;
3596  }
3597 
3598  // Check for need to substitute AltiVec keyword tokens.
3599  if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3600  break;
3601 
3602  // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3603  // allow the use of a typedef name as a type specifier.
3604  if (DS.isTypeAltiVecVector())
3605  goto DoneWithDeclSpec;
3606 
3607  if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3608  isObjCInstancetype()) {
3609  ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3610  assert(TypeRep);
3611  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3612  DiagID, TypeRep, Policy);
3613  if (isInvalid)
3614  break;
3615 
3616  DS.SetRangeEnd(Loc);
3617  ConsumeToken();
3618  continue;
3619  }
3620 
3621  // If we're in a context where the identifier could be a class name,
3622  // check whether this is a constructor declaration.
3623  if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3624  Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3625  isConstructorDeclarator(/*Unqualified=*/true,
3626  /*DeductionGuide=*/false,
3627  DS.isFriendSpecified()))
3628  goto DoneWithDeclSpec;
3629 
3630  ParsedType TypeRep = Actions.getTypeName(
3631  *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3632  false, false, nullptr, false, false,
3633  isClassTemplateDeductionContext(DSContext));
3634 
3635  // If this is not a typedef name, don't parse it as part of the declspec,
3636  // it must be an implicit int or an error.
3637  if (!TypeRep) {
3638  if (TryAnnotateTypeConstraint())
3639  goto DoneWithDeclSpec;
3640  if (Tok.isNot(tok::identifier))
3641  continue;
3642  ParsedAttributes Attrs(AttrFactory);
3643  if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3644  if (!Attrs.empty()) {
3645  AttrsLastTime = true;
3646  attrs.takeAllFrom(Attrs);
3647  }
3648  continue;
3649  }
3650  goto DoneWithDeclSpec;
3651  }
3652 
3653  // Likewise, if this is a context where the identifier could be a template
3654  // name, check whether this is a deduction guide declaration.
3655  if (getLangOpts().CPlusPlus17 &&
3656  (DSContext == DeclSpecContext::DSC_class ||
3657  DSContext == DeclSpecContext::DSC_top_level) &&
3659  Tok.getLocation()) &&
3660  isConstructorDeclarator(/*Unqualified*/ true,
3661  /*DeductionGuide*/ true))
3662  goto DoneWithDeclSpec;
3663 
3664  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3665  DiagID, TypeRep, Policy);
3666  if (isInvalid)
3667  break;
3668 
3669  DS.SetRangeEnd(Tok.getLocation());
3670  ConsumeToken(); // The identifier
3671 
3672  // Objective-C supports type arguments and protocol references
3673  // following an Objective-C object or object pointer
3674  // type. Handle either one of them.
3675  if (Tok.is(tok::less) && getLangOpts().ObjC) {
3676  SourceLocation NewEndLoc;
3677  TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3678  Loc, TypeRep, /*consumeLastToken=*/true,
3679  NewEndLoc);
3680  if (NewTypeRep.isUsable()) {
3681  DS.UpdateTypeRep(NewTypeRep.get());
3682  DS.SetRangeEnd(NewEndLoc);
3683  }
3684  }
3685 
3686  // Need to support trailing type qualifiers (e.g. "id<p> const").
3687  // If a type specifier follows, it will be diagnosed elsewhere.
3688  continue;
3689  }
3690 
3691  // type-name or placeholder-specifier
3692  case tok::annot_template_id: {
3693  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3694 
3695  if (TemplateId->hasInvalidName()) {
3696  DS.SetTypeSpecError();
3697  break;
3698  }
3699 
3700  if (TemplateId->Kind == TNK_Concept_template) {
3701  // If we've already diagnosed that this type-constraint has invalid
3702  // arguments, drop it and just form 'auto' or 'decltype(auto)'.
3703  if (TemplateId->hasInvalidArgs())
3704  TemplateId = nullptr;
3705 
3706  // Any of the following tokens are likely the start of the user
3707  // forgetting 'auto' or 'decltype(auto)', so diagnose.
3708  // Note: if updating this list, please make sure we update
3709  // isCXXDeclarationSpecifier's check for IsPlaceholderSpecifier to have
3710  // a matching list.
3711  if (NextToken().isOneOf(tok::identifier, tok::kw_const,
3712  tok::kw_volatile, tok::kw_restrict, tok::amp,
3713  tok::ampamp)) {
3714  Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3715  << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3716  // Attempt to continue as if 'auto' was placed here.
3717  isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3718  TemplateId, Policy);
3719  break;
3720  }
3721  if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3722  goto DoneWithDeclSpec;
3723  ConsumeAnnotationToken();
3724  SourceLocation AutoLoc = Tok.getLocation();
3725  if (TryConsumeToken(tok::kw_decltype)) {
3726  BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3727  if (Tracker.consumeOpen()) {
3728  // Something like `void foo(Iterator decltype i)`
3729  Diag(Tok, diag::err_expected) << tok::l_paren;
3730  } else {
3731  if (!TryConsumeToken(tok::kw_auto)) {
3732  // Something like `void foo(Iterator decltype(int) i)`
3733  Tracker.skipToEnd();
3734  Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3736  Tok.getLocation()),
3737  "auto");
3738  } else {
3739  Tracker.consumeClose();
3740  }
3741  }
3742  ConsumedEnd = Tok.getLocation();
3743  DS.setTypeArgumentRange(Tracker.getRange());
3744  // Even if something went wrong above, continue as if we've seen
3745  // `decltype(auto)`.
3746  isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3747  DiagID, TemplateId, Policy);
3748  } else {
3749  isInvalid = DS.SetTypeSpecType(TST_auto, AutoLoc, PrevSpec, DiagID,
3750  TemplateId, Policy);
3751  }
3752  break;
3753  }
3754 
3755  if (TemplateId->Kind != TNK_Type_template &&
3756  TemplateId->Kind != TNK_Undeclared_template) {
3757  // This template-id does not refer to a type name, so we're
3758  // done with the type-specifiers.
3759  goto DoneWithDeclSpec;
3760  }
3761 
3762  // If we're in a context where the template-id could be a
3763  // constructor name or specialization, check whether this is a
3764  // constructor declaration.
3765  if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3766  Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3767  isConstructorDeclarator(/*Unqualified=*/true,
3768  /*DeductionGuide=*/false,
3769  DS.isFriendSpecified()))
3770  goto DoneWithDeclSpec;
3771 
3772  // Turn the template-id annotation token into a type annotation
3773  // token, then try again to parse it as a type-specifier.
3774  CXXScopeSpec SS;
3775  AnnotateTemplateIdTokenAsType(SS, AllowImplicitTypename);
3776  continue;
3777  }
3778 
3779  // Attributes support.
3780  case tok::kw___attribute:
3781  case tok::kw___declspec:
3782  ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), LateAttrs);
3783  continue;
3784 
3785  // Microsoft single token adornments.
3786  case tok::kw___forceinline: {
3787  isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3788  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3789  SourceLocation AttrNameLoc = Tok.getLocation();
3790  DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3791  nullptr, 0, ParsedAttr::AS_Keyword);
3792  break;
3793  }
3794 
3795  case tok::kw___unaligned:
3796  isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3797  getLangOpts());
3798  break;
3799 
3800  case tok::kw___sptr:
3801  case tok::kw___uptr:
3802  case tok::kw___ptr64:
3803  case tok::kw___ptr32:
3804  case tok::kw___w64:
3805  case tok::kw___cdecl:
3806  case tok::kw___stdcall:
3807  case tok::kw___fastcall:
3808  case tok::kw___thiscall:
3809  case tok::kw___regcall:
3810  case tok::kw___vectorcall:
3811  ParseMicrosoftTypeAttributes(DS.getAttributes());
3812  continue;
3813 
3814  // Borland single token adornments.
3815  case tok::kw___pascal:
3816  ParseBorlandTypeAttributes(DS.getAttributes());
3817  continue;
3818 
3819  // OpenCL single token adornments.
3820  case tok::kw___kernel:
3821  ParseOpenCLKernelAttributes(DS.getAttributes());
3822  continue;
3823 
3824  // CUDA/HIP single token adornments.
3825  case tok::kw___noinline__:
3826  ParseCUDAFunctionAttributes(DS.getAttributes());
3827  continue;
3828 
3829  // Nullability type specifiers.
3830  case tok::kw__Nonnull:
3831  case tok::kw__Nullable:
3832  case tok::kw__Nullable_result:
3833  case tok::kw__Null_unspecified:
3834  ParseNullabilityTypeSpecifiers(DS.getAttributes());
3835  continue;
3836 
3837  // Objective-C 'kindof' types.
3838  case tok::kw___kindof:
3839  DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3840  nullptr, 0, ParsedAttr::AS_Keyword);
3841  (void)ConsumeToken();
3842  continue;
3843 
3844  // storage-class-specifier
3845  case tok::kw_typedef:
3847  PrevSpec, DiagID, Policy);
3848  isStorageClass = true;
3849  break;
3850  case tok::kw_extern:
3852  Diag(Tok, diag::ext_thread_before) << "extern";
3854  PrevSpec, DiagID, Policy);
3855  isStorageClass = true;
3856  break;
3857  case tok::kw___private_extern__:
3859  Loc, PrevSpec, DiagID, Policy);
3860  isStorageClass = true;
3861  break;
3862  case tok::kw_static:
3864  Diag(Tok, diag::ext_thread_before) << "static";
3866  PrevSpec, DiagID, Policy);
3867  isStorageClass = true;
3868  break;
3869  case tok::kw_auto:
3870  if (getLangOpts().CPlusPlus11) {
3871  if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3873  PrevSpec, DiagID, Policy);
3874  if (!isInvalid)
3875  Diag(Tok, diag::ext_auto_storage_class)
3877  } else
3878  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3879  DiagID, Policy);
3880  } else
3882  PrevSpec, DiagID, Policy);
3883  isStorageClass = true;
3884  break;
3885  case tok::kw___auto_type:
3886  Diag(Tok, diag::ext_auto_type);
3888  DiagID, Policy);
3889  break;
3890  case tok::kw_register:
3892  PrevSpec, DiagID, Policy);
3893  isStorageClass = true;
3894  break;
3895  case tok::kw_mutable:
3897  PrevSpec, DiagID, Policy);
3898  isStorageClass = true;
3899  break;
3900  case tok::kw___thread:
3902  PrevSpec, DiagID);
3903  isStorageClass = true;
3904  break;
3905  case tok::kw_thread_local:
3907  PrevSpec, DiagID);
3908  isStorageClass = true;
3909  break;
3910  case tok::kw__Thread_local:
3911  if (!getLangOpts().C11)
3912  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3914  Loc, PrevSpec, DiagID);
3915  isStorageClass = true;
3916  break;
3917 
3918  // function-specifier
3919  case tok::kw_inline:
3920  isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3921  break;
3922  case tok::kw_virtual:
3923  // C++ for OpenCL does not allow virtual function qualifier, to avoid
3924  // function pointers restricted in OpenCL v2.0 s6.9.a.
3925  if (getLangOpts().OpenCLCPlusPlus &&
3926  !getActions().getOpenCLOptions().isAvailableOption(
3927  "__cl_clang_function_pointers", getLangOpts())) {
3928  DiagID = diag::err_openclcxx_virtual_function;
3929  PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3930  isInvalid = true;
3931  } else {
3932  isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3933  }
3934  break;
3935  case tok::kw_explicit: {
3936  SourceLocation ExplicitLoc = Loc;
3937  SourceLocation CloseParenLoc;
3938  ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3939  ConsumedEnd = ExplicitLoc;
3940  ConsumeToken(); // kw_explicit
3941  if (Tok.is(tok::l_paren)) {
3942  if (getLangOpts().CPlusPlus20 || isExplicitBool() == TPResult::True) {
3944  ? diag::warn_cxx17_compat_explicit_bool
3945  : diag::ext_explicit_bool);
3946 
3947  ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3948  BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3949  Tracker.consumeOpen();
3950  ExplicitExpr = ParseConstantExpression();
3951  ConsumedEnd = Tok.getLocation();
3952  if (ExplicitExpr.isUsable()) {
3953  CloseParenLoc = Tok.getLocation();
3954  Tracker.consumeClose();
3955  ExplicitSpec =
3956  Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3957  } else
3958  Tracker.skipToEnd();
3959  } else {
3960  Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
3961  }
3962  }
3963  isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3964  ExplicitSpec, CloseParenLoc);
3965  break;
3966  }
3967  case tok::kw__Noreturn:
3968  if (!getLangOpts().C11)
3969  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3970  isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3971  break;
3972 
3973  // alignment-specifier
3974  case tok::kw__Alignas:
3975  if (!getLangOpts().C11)
3976  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3977  ParseAlignmentSpecifier(DS.getAttributes());
3978  continue;
3979 
3980  // friend
3981  case tok::kw_friend:
3982  if (DSContext == DeclSpecContext::DSC_class)
3983  isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3984  else {
3985  PrevSpec = ""; // not actually used by the diagnostic
3986  DiagID = diag::err_friend_invalid_in_context;
3987  isInvalid = true;
3988  }
3989  break;
3990 
3991  // Modules
3992  case tok::kw___module_private__:
3993  isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3994  break;
3995 
3996  // constexpr, consteval, constinit specifiers
3997  case tok::kw_constexpr:
3999  PrevSpec, DiagID);
4000  break;
4001  case tok::kw_consteval:
4003  PrevSpec, DiagID);
4004  break;
4005  case tok::kw_constinit:
4007  PrevSpec, DiagID);
4008  break;
4009 
4010  // type-specifier
4011  case tok::kw_short:
4013  DiagID, Policy);
4014  break;
4015  case tok::kw_long:
4018  DiagID, Policy);
4019  else
4021  PrevSpec, DiagID, Policy);
4022  break;
4023  case tok::kw___int64:
4025  PrevSpec, DiagID, Policy);
4026  break;
4027  case tok::kw_signed:
4028  isInvalid =
4029  DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
4030  break;
4031  case tok::kw_unsigned:
4033  DiagID);
4034  break;
4035  case tok::kw__Complex:
4036  if (!getLangOpts().C99)
4037  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4039  DiagID);
4040  break;
4041  case tok::kw__Imaginary:
4042  if (!getLangOpts().C99)
4043  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4045  DiagID);
4046  break;
4047  case tok::kw_void:
4048  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
4049  DiagID, Policy);
4050  break;
4051  case tok::kw_char:
4052  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
4053  DiagID, Policy);
4054  break;
4055  case tok::kw_int:
4056  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
4057  DiagID, Policy);
4058  break;
4059  case tok::kw__ExtInt:
4060  case tok::kw__BitInt: {
4061  DiagnoseBitIntUse(Tok);
4062  ExprResult ER = ParseExtIntegerArgument();
4063  if (ER.isInvalid())
4064  continue;
4065  isInvalid = DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
4066  ConsumedEnd = PrevTokLocation;
4067  break;
4068  }
4069  case tok::kw___int128:
4070  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
4071  DiagID, Policy);
4072  break;
4073  case tok::kw_half:
4074  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
4075  DiagID, Policy);
4076  break;
4077  case tok::kw___bf16:
4078  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec,
4079  DiagID, Policy);
4080  break;
4081  case tok::kw_float:
4082  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
4083  DiagID, Policy);
4084  break;
4085  case tok::kw_double:
4086  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
4087  DiagID, Policy);
4088  break;
4089  case tok::kw__Float16:
4090  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
4091  DiagID, Policy);
4092  break;
4093  case tok::kw__Accum:
4094  if (!getLangOpts().FixedPoint) {
4095  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4096  } else {
4097  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
4098  DiagID, Policy);
4099  }
4100  break;
4101  case tok::kw__Fract:
4102  if (!getLangOpts().FixedPoint) {
4103  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4104  } else {
4105  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
4106  DiagID, Policy);
4107  }
4108  break;
4109  case tok::kw__Sat:
4110  if (!getLangOpts().FixedPoint) {
4111  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
4112  } else {
4113  isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
4114  }
4115  break;
4116  case tok::kw___float128:
4117  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
4118  DiagID, Policy);
4119  break;
4120  case tok::kw___ibm128:
4121  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec,
4122  DiagID, Policy);
4123  break;
4124  case tok::kw_wchar_t:
4125  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
4126  DiagID, Policy);
4127  break;
4128  case tok::kw_char8_t:
4129  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
4130  DiagID, Policy);
4131  break;
4132  case tok::kw_char16_t:
4133  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
4134  DiagID, Policy);
4135  break;
4136  case tok::kw_char32_t:
4137  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
4138  DiagID, Policy);
4139  break;
4140  case tok::kw_bool:
4141  case tok::kw__Bool:
4142  if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
4143  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
4144 
4145  if (Tok.is(tok::kw_bool) &&
4148  PrevSpec = ""; // Not used by the diagnostic.
4149  DiagID = diag::err_bool_redeclaration;
4150  // For better error recovery.
4151  Tok.setKind(tok::identifier);
4152  isInvalid = true;
4153  } else {
4154  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
4155  DiagID, Policy);
4156  }
4157  break;
4158  case tok::kw__Decimal32:
4160  DiagID, Policy);
4161  break;
4162  case tok::kw__Decimal64:
4164  DiagID, Policy);
4165  break;
4166  case tok::kw__Decimal128:
4168  DiagID, Policy);
4169  break;
4170  case tok::kw___vector:
4171  isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
4172  break;
4173  case tok::kw___pixel:
4174  isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
4175  break;
4176  case tok::kw___bool:
4177  isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
4178  break;
4179  case tok::kw_pipe:
4180  if (!getLangOpts().OpenCL ||
4181  getLangOpts().getOpenCLCompatibleVersion() < 200) {
4182  // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
4183  // should support the "pipe" word as identifier.
4185  Tok.setKind(tok::identifier);
4186  goto DoneWithDeclSpec;
4187  } else if (!getLangOpts().OpenCLPipes) {
4188  DiagID = diag::err_opencl_unknown_type_specifier;
4189  PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4190  isInvalid = true;
4191  } else
4192  isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4193  break;
4194 // We only need to enumerate each image type once.
4195 #define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4196 #define IMAGE_WRITE_TYPE(Type, Id, Ext)
4197 #define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4198  case tok::kw_##ImgType##_t: \
4199  if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4200  goto DoneWithDeclSpec; \
4201  break;
4202 #include "clang/Basic/OpenCLImageTypes.def"
4203  case tok::kw___unknown_anytype:
4205  PrevSpec, DiagID, Policy);
4206  break;
4207 
4208  // class-specifier:
4209  case tok::kw_class:
4210  case tok::kw_struct:
4211  case tok::kw___interface:
4212  case tok::kw_union: {
4213  tok::TokenKind Kind = Tok.getKind();
4214  ConsumeToken();
4215 
4216  // These are attributes following class specifiers.
4217  // To produce better diagnostic, we parse them when
4218  // parsing class specifier.
4219  ParsedAttributes Attributes(AttrFactory);
4220  ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4221  EnteringContext, DSContext, Attributes);
4222 
4223  // If there are attributes following class specifier,
4224  // take them over and handle them here.
4225  if (!Attributes.empty()) {
4226  AttrsLastTime = true;
4227  attrs.takeAllFrom(Attributes);
4228  }
4229  continue;
4230  }
4231 
4232  // enum-specifier:
4233  case tok::kw_enum:
4234  ConsumeToken();
4235  ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4236  continue;
4237 
4238  // cv-qualifier:
4239  case tok::kw_const:
4240  isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4241  getLangOpts());
4242  break;
4243  case tok::kw_volatile:
4244  isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4245  getLangOpts());
4246  break;
4247  case tok::kw_restrict:
4248  isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4249  getLangOpts());
4250  break;
4251 
4252  // C++ typename-specifier:
4253  case tok::kw_typename:
4255  DS.SetTypeSpecError();
4256  goto DoneWithDeclSpec;
4257  }
4258  if (!Tok.is(tok::kw_typename))
4259  continue;
4260  break;
4261 
4262  // C2x/GNU typeof support.
4263  case tok::kw_typeof:
4264  case tok::kw_typeof_unqual:
4265  ParseTypeofSpecifier(DS);
4266  continue;
4267 
4268  case tok::annot_decltype:
4269  ParseDecltypeSpecifier(DS);
4270  continue;
4271 
4272  case tok::annot_pragma_pack:
4273  HandlePragmaPack();
4274  continue;
4275 
4276  case tok::annot_pragma_ms_pragma:
4277  HandlePragmaMSPragma();
4278  continue;
4279 
4280  case tok::annot_pragma_ms_vtordisp:
4281  HandlePragmaMSVtorDisp();
4282  continue;
4283 
4284  case tok::annot_pragma_ms_pointers_to_members:
4285  HandlePragmaMSPointersToMembers();
4286  continue;
4287 
4288 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
4289 #include "clang/Basic/TransformTypeTraits.def"
4290  // HACK: libstdc++ already uses '__remove_cv' as an alias template so we
4291  // work around this by expecting all transform type traits to be suffixed
4292  // with '('. They're an identifier otherwise.
4293  if (!MaybeParseTypeTransformTypeSpecifier(DS))
4294  goto ParseIdentifier;
4295  continue;
4296 
4297  case tok::kw__Atomic:
4298  // C11 6.7.2.4/4:
4299  // If the _Atomic keyword is immediately followed by a left parenthesis,
4300  // it is interpreted as a type specifier (with a type name), not as a
4301  // type qualifier.
4302  if (!getLangOpts().C11)
4303  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4304 
4305  if (NextToken().is(tok::l_paren)) {
4306  ParseAtomicSpecifier(DS);
4307  continue;
4308  }
4309  isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4310  getLangOpts());
4311  break;
4312 
4313  // OpenCL address space qualifiers:
4314  case tok::kw___generic:
4315  // generic address space is introduced only in OpenCL v2.0
4316  // see OpenCL C Spec v2.0 s6.5.5
4317  // OpenCL v3.0 introduces __opencl_c_generic_address_space
4318  // feature macro to indicate if generic address space is supported
4319  if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4320  DiagID = diag::err_opencl_unknown_type_specifier;
4321  PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4322  isInvalid = true;
4323  break;
4324  }
4325  [[fallthrough]];
4326  case tok::kw_private:
4327  // It's fine (but redundant) to check this for __generic on the
4328  // fallthrough path; we only form the __generic token in OpenCL mode.
4329  if (!getLangOpts().OpenCL)
4330  goto DoneWithDeclSpec;
4331  [[fallthrough]];
4332  case tok::kw___private:
4333  case tok::kw___global:
4334  case tok::kw___local:
4335  case tok::kw___constant:
4336  // OpenCL access qualifiers:
4337  case tok::kw___read_only:
4338  case tok::kw___write_only:
4339  case tok::kw___read_write:
4340  ParseOpenCLQualifiers(DS.getAttributes());
4341  break;
4342 
4343  case tok::kw_groupshared:
4344  // NOTE: ParseHLSLQualifiers will consume the qualifier token.
4345  ParseHLSLQualifiers(DS.getAttributes());
4346  continue;
4347 
4348  case tok::less:
4349  // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4350  // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
4351  // but we support it.
4352  if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
4353  goto DoneWithDeclSpec;
4354 
4355  SourceLocation StartLoc = Tok.getLocation();
4356  SourceLocation EndLoc;
4357  TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4358  if (Type.isUsable()) {
4359  if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4360  PrevSpec, DiagID, Type.get(),
4361  Actions.getASTContext().getPrintingPolicy()))
4362  Diag(StartLoc, DiagID) << PrevSpec;
4363 
4364  DS.SetRangeEnd(EndLoc);
4365  } else {
4366  DS.SetTypeSpecError();
4367  }
4368 
4369  // Need to support trailing type qualifiers (e.g. "id<p> const").
4370  // If a type specifier follows, it will be diagnosed elsewhere.
4371  continue;
4372  }
4373 
4374  DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4375 
4376  // If the specifier wasn't legal, issue a diagnostic.
4377  if (isInvalid) {
4378  assert(PrevSpec && "Method did not return previous specifier!");
4379  assert(DiagID);
4380 
4381  if (DiagID == diag::ext_duplicate_declspec ||
4382  DiagID == diag::ext_warn_duplicate_declspec ||
4383  DiagID == diag::err_duplicate_declspec)
4384  Diag(Loc, DiagID) << PrevSpec
4386  SourceRange(Loc, DS.getEndLoc()));
4387  else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4388  Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4389  << isStorageClass;
4390  } else
4391  Diag(Loc, DiagID) << PrevSpec;
4392  }
4393 
4394  if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4395  // After an error the next token can be an annotation token.
4396  ConsumeAnyToken();
4397 
4398  AttrsLastTime = false;
4399  }
4400 }
4401 
4402 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4403 /// semicolon.
4404 ///
4405 /// Note that a struct declaration refers to a declaration in a struct,
4406 /// not to the declaration of a struct.
4407 ///
4408 /// struct-declaration:
4409 /// [C2x] attributes-specifier-seq[opt]
4410 /// specifier-qualifier-list struct-declarator-list
4411 /// [GNU] __extension__ struct-declaration
4412 /// [GNU] specifier-qualifier-list
4413 /// struct-declarator-list:
4414 /// struct-declarator
4415 /// struct-declarator-list ',' struct-declarator
4416 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4417 /// struct-declarator:
4418 /// declarator
4419 /// [GNU] declarator attributes[opt]
4420 /// declarator[opt] ':' constant-expression
4421 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4422 ///
4423 void Parser::ParseStructDeclaration(
4424  ParsingDeclSpec &DS,
4425  llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4426 
4427  if (Tok.is(tok::kw___extension__)) {
4428  // __extension__ silences extension warnings in the subexpression.
4429  ExtensionRAIIObject O(Diags); // Use RAII to do this.
4430  ConsumeToken();
4431  return ParseStructDeclaration(DS, FieldsCallback);
4432  }
4433 
4434  // Parse leading attributes.
4435  ParsedAttributes Attrs(AttrFactory);
4436  MaybeParseCXX11Attributes(Attrs);
4437 
4438  // Parse the common specifier-qualifiers-list piece.
4439  ParseSpecifierQualifierList(DS);
4440 
4441  // If there are no declarators, this is a free-standing declaration
4442  // specifier. Let the actions module cope with it.
4443  if (Tok.is(tok::semi)) {
4444  // C2x 6.7.2.1p9 : "The optional attribute specifier sequence in a
4445  // member declaration appertains to each of the members declared by the
4446  // member declarator list; it shall not appear if the optional member
4447  // declarator list is omitted."
4448  ProhibitAttributes(Attrs);
4449  RecordDecl *AnonRecord = nullptr;
4450  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
4451  getCurScope(), AS_none, DS, ParsedAttributesView::none(), AnonRecord);
4452  assert(!AnonRecord && "Did not expect anonymous struct or union here");
4453  DS.complete(TheDecl);
4454  return;
4455  }
4456 
4457  // Read struct-declarators until we find the semicolon.
4458  bool FirstDeclarator = true;
4459  SourceLocation CommaLoc;
4460  while (true) {
4461  ParsingFieldDeclarator DeclaratorInfo(*this, DS, Attrs);
4462  DeclaratorInfo.D.setCommaLoc(CommaLoc);
4463 
4464  // Attributes are only allowed here on successive declarators.
4465  if (!FirstDeclarator) {
4466  // However, this does not apply for [[]] attributes (which could show up
4467  // before or after the __attribute__ attributes).
4468  DiagnoseAndSkipCXX11Attributes();
4469  MaybeParseGNUAttributes(DeclaratorInfo.D);
4470  DiagnoseAndSkipCXX11Attributes();
4471  }
4472 
4473  /// struct-declarator: declarator
4474  /// struct-declarator: declarator[opt] ':' constant-expression
4475  if (Tok.isNot(tok::colon)) {
4476  // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4478  ParseDeclarator(DeclaratorInfo.D);
4479  } else
4480  DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4481 
4482  if (TryConsumeToken(tok::colon)) {
4484  if (Res.isInvalid())
4485  SkipUntil(tok::semi, StopBeforeMatch);
4486  else
4487  DeclaratorInfo.BitfieldSize = Res.get();
4488  }
4489 
4490  // If attributes exist after the declarator, parse them.
4491  MaybeParseGNUAttributes(DeclaratorInfo.D);
4492 
4493  // We're done with this declarator; invoke the callback.
4494  FieldsCallback(DeclaratorInfo);
4495 
4496  // If we don't have a comma, it is either the end of the list (a ';')
4497  // or an error, bail out.
4498  if (!TryConsumeToken(tok::comma, CommaLoc))
4499  return;
4500 
4501  FirstDeclarator = false;
4502  }
4503 }
4504 
4505 /// ParseStructUnionBody
4506 /// struct-contents:
4507 /// struct-declaration-list
4508 /// [EXT] empty
4509 /// [GNU] "struct-declaration-list" without terminating ';'
4510 /// struct-declaration-list:
4511 /// struct-declaration
4512 /// struct-declaration-list struct-declaration
4513 /// [OBC] '@' 'defs' '(' class-name ')'
4514 ///
4515 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4517  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4518  "parsing struct/union body");
4519  assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4520 
4521  BalancedDelimiterTracker T(*this, tok::l_brace);
4522  if (T.consumeOpen())
4523  return;
4524 
4525  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4527 
4528  // While we still have something to read, read the declarations in the struct.
4529  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4530  Tok.isNot(tok::eof)) {
4531  // Each iteration of this loop reads one struct-declaration.
4532 
4533  // Check for extraneous top-level semicolon.
4534  if (Tok.is(tok::semi)) {
4535  ConsumeExtraSemi(InsideStruct, TagType);
4536  continue;
4537  }
4538 
4539  // Parse _Static_assert declaration.
4540  if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
4541  SourceLocation DeclEnd;
4542  ParseStaticAssertDeclaration(DeclEnd);
4543  continue;
4544  }
4545 
4546  if (Tok.is(tok::annot_pragma_pack)) {
4547  HandlePragmaPack();
4548  continue;
4549  }
4550 
4551  if (Tok.is(tok::annot_pragma_align)) {
4552  HandlePragmaAlign();
4553  continue;
4554  }
4555 
4556  if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
4557  // Result can be ignored, because it must be always empty.
4558  AccessSpecifier AS = AS_none;
4559  ParsedAttributes Attrs(AttrFactory);
4560  (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4561  continue;
4562  }
4563 
4564  if (tok::isPragmaAnnotation(Tok.getKind())) {
4565  Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4567  TagType, Actions.getASTContext().getPrintingPolicy());
4568  ConsumeAnnotationToken();
4569  continue;
4570  }
4571 
4572  if (!Tok.is(tok::at)) {
4573  auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4574  // Install the declarator into the current TagDecl.
4575  Decl *Field =
4576  Actions.ActOnField(getCurScope(), TagDecl,
4577  FD.D.getDeclSpec().getSourceRange().getBegin(),
4578  FD.D, FD.BitfieldSize);
4579  FD.complete(Field);
4580  };
4581 
4582  // Parse all the comma separated declarators.
4583  ParsingDeclSpec DS(*this);
4584  ParseStructDeclaration(DS, CFieldCallback);
4585  } else { // Handle @defs
4586  ConsumeToken();
4587  if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4588  Diag(Tok, diag::err_unexpected_at);
4589  SkipUntil(tok::semi);
4590  continue;
4591  }
4592  ConsumeToken();
4593  ExpectAndConsume(tok::l_paren);
4594  if (!Tok.is(tok::identifier)) {
4595  Diag(Tok, diag::err_expected) << tok::identifier;
4596  SkipUntil(tok::semi);
4597  continue;
4598  }
4599  SmallVector<Decl *, 16> Fields;
4600  Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4601  Tok.getIdentifierInfo(), Fields);
4602  ConsumeToken();
4603  ExpectAndConsume(tok::r_paren);
4604  }
4605 
4606  if (TryConsumeToken(tok::semi))
4607  continue;
4608 
4609  if (Tok.is(tok::r_brace)) {
4610  ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4611  break;
4612  }
4613 
4614  ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4615  // Skip to end of block or statement to avoid ext-warning on extra ';'.
4616  SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4617  // If we stopped at a ';', eat it.
4618  TryConsumeToken(tok::semi);
4619  }
4620 
4621  T.consumeClose();
4622 
4623  ParsedAttributes attrs(AttrFactory);
4624  // If attributes exist after struct contents, parse them.
4625  MaybeParseGNUAttributes(attrs);
4626 
4627  SmallVector<Decl *, 32> FieldDecls(TagDecl->fields());
4628 
4629  Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4630  T.getOpenLocation(), T.getCloseLocation(), attrs);
4631  StructScope.Exit();
4632  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4633 }
4634 
4635 /// ParseEnumSpecifier
4636 /// enum-specifier: [C99 6.7.2.2]
4637 /// 'enum' identifier[opt] '{' enumerator-list '}'
4638 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4639 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4640 /// '}' attributes[opt]
4641 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4642 /// '}'
4643 /// 'enum' identifier
4644 /// [GNU] 'enum' attributes[opt] identifier
4645 ///
4646 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4647 /// [C++11] enum-head '{' enumerator-list ',' '}'
4648 ///
4649 /// enum-head: [C++11]
4650 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4651 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4652 /// identifier enum-base[opt]
4653 ///
4654 /// enum-key: [C++11]
4655 /// 'enum'
4656 /// 'enum' 'class'
4657 /// 'enum' 'struct'
4658 ///
4659 /// enum-base: [C++11]
4660 /// ':' type-specifier-seq
4661 ///
4662 /// [C++] elaborated-type-specifier:
4663 /// [C++] 'enum' nested-name-specifier[opt] identifier
4664 ///
4665 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4666  const ParsedTemplateInfo &TemplateInfo,
4667  AccessSpecifier AS, DeclSpecContext DSC) {
4668  // Parse the tag portion of this.
4669  if (Tok.is(tok::code_completion)) {
4670  // Code completion for an enum name.
4671  cutOffParsing();
4673  DS.SetTypeSpecError(); // Needed by ActOnUsingDeclaration.
4674  return;
4675  }
4676 
4677  // If attributes exist after tag, parse them.
4678  ParsedAttributes attrs(AttrFactory);
4679  MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4680 
4681  SourceLocation ScopedEnumKWLoc;
4682  bool IsScopedUsingClassTag = false;
4683 
4684  // In C++11, recognize 'enum class' and 'enum struct'.
4685  if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
4686  Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4687  : diag::ext_scoped_enum);
4688  IsScopedUsingClassTag = Tok.is(tok::kw_class);
4689  ScopedEnumKWLoc = ConsumeToken();
4690 
4691  // Attributes are not allowed between these keywords. Diagnose,
4692  // but then just treat them like they appeared in the right place.
4693  ProhibitAttributes(attrs);
4694 
4695  // They are allowed afterwards, though.
4696  MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4697  }
4698 
4699  // C++11 [temp.explicit]p12:
4700  // The usual access controls do not apply to names used to specify
4701  // explicit instantiations.
4702  // We extend this to also cover explicit specializations. Note that
4703  // we don't suppress if this turns out to be an elaborated type
4704  // specifier.
4705  bool shouldDelayDiagsInTag =
4706  (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4707  TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4708  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4709 
4710  // Determine whether this declaration is permitted to have an enum-base.
4711  AllowDefiningTypeSpec AllowEnumSpecifier =
4712  isDefiningTypeSpecifierContext(DSC, getLangOpts().CPlusPlus);
4713  bool CanBeOpaqueEnumDeclaration =
4714  DS.isEmpty() && isOpaqueEnumDeclarationContext(DSC);
4715  bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || getLangOpts().ObjC ||
4716  getLangOpts().MicrosoftExt) &&
4717  (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes ||
4718  CanBeOpaqueEnumDeclaration);
4719 
4720  CXXScopeSpec &SS = DS.getTypeSpecScope();
4721  if (getLangOpts().CPlusPlus) {
4722  // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
4724 
4725  CXXScopeSpec Spec;
4726  if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
4727  /*ObjectHasErrors=*/false,
4728  /*EnteringContext=*/true))
4729  return;
4730 
4731  if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4732  Diag(Tok, diag::err_expected) << tok::identifier;
4733  DS.SetTypeSpecError();
4734  if (Tok.isNot(tok::l_brace)) {
4735  // Has no name and is not a definition.
4736  // Skip the rest of this declarator, up until the comma or semicolon.
4737  SkipUntil(tok::comma, StopAtSemi);
4738  return;
4739  }
4740  }
4741 
4742  SS = Spec;
4743  }
4744 
4745  // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
4746  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4747  Tok.isNot(tok::colon)) {
4748  Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4749 
4750  DS.SetTypeSpecError();
4751  // Skip the rest of this declarator, up until the comma or semicolon.
4752  SkipUntil(tok::comma, StopAtSemi);
4753  return;
4754  }
4755 
4756  // If an identifier is present, consume and remember it.
4757  IdentifierInfo *Name = nullptr;
4758  SourceLocation NameLoc;
4759  if (Tok.is(tok::identifier)) {
4760  Name = Tok.getIdentifierInfo();
4761  NameLoc = ConsumeToken();
4762  }
4763 
4764  if (!Name && ScopedEnumKWLoc.isValid()) {
4765  // C++0x 7.2p2: The optional identifier shall not be omitted in the
4766  // declaration of a scoped enumeration.
4767  Diag(Tok, diag::err_scoped_enum_missing_identifier);
4768  ScopedEnumKWLoc = SourceLocation();
4769  IsScopedUsingClassTag = false;
4770  }
4771 
4772  // Okay, end the suppression area. We'll decide whether to emit the
4773  // diagnostics in a second.
4774  if (shouldDelayDiagsInTag)
4775  diagsFromTag.done();
4776 
4777  TypeResult BaseType;
4778  SourceRange BaseRange;
4779 
4780  bool CanBeBitfield =
4781  getCurScope()->isClassScope() && ScopedEnumKWLoc.isInvalid() && Name;
4782 
4783  // Parse the fixed underlying type.
4784  if (Tok.is(tok::colon)) {
4785  // This might be an enum-base or part of some unrelated enclosing context.
4786  //
4787  // 'enum E : base' is permitted in two circumstances:
4788  //
4789  // 1) As a defining-type-specifier, when followed by '{'.
4790  // 2) As the sole constituent of a complete declaration -- when DS is empty
4791  // and the next token is ';'.
4792  //
4793  // The restriction to defining-type-specifiers is important to allow parsing
4794  // a ? new enum E : int{}
4795  // _Generic(a, enum E : int{})
4796  // properly.
4797  //
4798  // One additional consideration applies:
4799  //
4800  // C++ [dcl.enum]p1:
4801  // A ':' following "enum nested-name-specifier[opt] identifier" within
4802  // the decl-specifier-seq of a member-declaration is parsed as part of
4803  // an enum-base.
4804  //
4805  // Other language modes supporting enumerations with fixed underlying types
4806  // do not have clear rules on this, so we disambiguate to determine whether
4807  // the tokens form a bit-field width or an enum-base.
4808 
4809  if (CanBeBitfield && !isEnumBase(CanBeOpaqueEnumDeclaration)) {
4810  // Outside C++11, do not interpret the tokens as an enum-base if they do
4811  // not make sense as one. In C++11, it's an error if this happens.
4812  if (getLangOpts().CPlusPlus11)
4813  Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
4814  } else if (CanHaveEnumBase || !ColonIsSacred) {
4815  SourceLocation ColonLoc = ConsumeToken();
4816 
4817  // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
4818  // because under -fms-extensions,
4819  // enum E : int *p;
4820  // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
4821  DeclSpec DS(AttrFactory);
4822  // enum-base is not assumed to be a type and therefore requires the
4823  // typename keyword [p0634r3].
4824  ParseSpecifierQualifierList(DS, ImplicitTypenameContext::No, AS,
4825  DeclSpecContext::DSC_type_specifier);
4826  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
4828  BaseType = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
4829 
4830  BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
4831 
4832  if (!getLangOpts().ObjC) {
4833  if (getLangOpts().CPlusPlus11)
4834  Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
4835  << BaseRange;
4836  else if (getLangOpts().CPlusPlus)
4837  Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
4838  << BaseRange;
4839  else if (getLangOpts().MicrosoftExt)
4840  Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
4841  << BaseRange;
4842  else
4843  Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
4844  << BaseRange;
4845  }
4846  }
4847  }
4848 
4849  // There are four options here. If we have 'friend enum foo;' then this is a
4850  // friend declaration, and cannot have an accompanying definition. If we have
4851  // 'enum foo;', then this is a forward declaration. If we have
4852  // 'enum foo {...' then this is a definition. Otherwise we have something
4853  // like 'enum foo xyz', a reference.
4854  //
4855  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4856  // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4857  // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4858  //
4859  Sema::TagUseKind TUK;
4860  if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
4861  TUK = Sema::TUK_Reference;
4862  else if (Tok.is(tok::l_brace)) {
4863  if (DS.isFriendSpecified()) {
4864  Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4865  << SourceRange(DS.getFriendSpecLoc());
4866  ConsumeBrace();
4867  SkipUntil(tok::r_brace, StopAtSemi);
4868  // Discard any other definition-only pieces.
4869  attrs.clear();
4870  ScopedEnumKWLoc = SourceLocation();
4871  IsScopedUsingClassTag = false;
4872  BaseType = TypeResult();
4873  TUK = Sema::TUK_Friend;
4874  } else {
4875  TUK = Sema::TUK_Definition;
4876  }
4877  } else if (!isTypeSpecifier(DSC) &&
4878  (Tok.is(tok::semi) ||
4879  (Tok.isAtStartOfLine() &&
4880  !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4881  // An opaque-enum-declaration is required to be standalone (no preceding or
4882  // following tokens in the declaration). Sema enforces this separately by
4883  // diagnosing anything else in the DeclSpec.
4885  if (Tok.isNot(tok::semi)) {
4886  // A semicolon was missing after this declaration. Diagnose and recover.
4887  ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4888  PP.EnterToken(Tok, /*IsReinject=*/true);
4889  Tok.setKind(tok::semi);
4890  }
4891  } else {
4892  TUK = Sema::TUK_Reference;
4893  }
4894 
4895  bool IsElaboratedTypeSpecifier =
4896  TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend;
4897 
4898  // If this is an elaborated type specifier nested in a larger declaration,
4899  // and we delayed diagnostics before, just merge them into the current pool.
4900  if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4901  diagsFromTag.redelay();
4902  }
4903 
4904  MultiTemplateParamsArg TParams;
4905  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4906  TUK != Sema::TUK_Reference) {
4907  if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4908  // Skip the rest of this declarator, up until the comma or semicolon.
4909  Diag(Tok, diag::err_enum_template);
4910  SkipUntil(tok::comma, StopAtSemi);
4911  return;
4912  }
4913 
4914  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4915  // Enumerations can't be explicitly instantiated.
4916  DS.SetTypeSpecError();
4917  Diag(StartLoc, diag::err_explicit_instantiation_enum);
4918  return;
4919  }
4920 
4921  assert(TemplateInfo.TemplateParams && "no template parameters");
4922  TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4923  TemplateInfo.TemplateParams->size());
4924  }
4925 
4926  if (!Name && TUK != Sema::TUK_Definition) {
4927  Diag(Tok, diag::err_enumerator_unnamed_no_def);
4928 
4929  DS.SetTypeSpecError();
4930  // Skip the rest of this declarator, up until the comma or semicolon.
4931  SkipUntil(tok::comma, StopAtSemi);
4932  return;
4933  }
4934 
4935  // An elaborated-type-specifier has a much more constrained grammar:
4936  //
4937  // 'enum' nested-name-specifier[opt] identifier
4938  //
4939  // If we parsed any other bits, reject them now.
4940  //
4941  // MSVC and (for now at least) Objective-C permit a full enum-specifier
4942  // or opaque-enum-declaration anywhere.
4943  if (IsElaboratedTypeSpecifier && !getLangOpts().MicrosoftExt &&
4944  !getLangOpts().ObjC) {
4945  ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
4946  /*DiagnoseEmptyAttrs=*/true);
4947  if (BaseType.isUsable())
4948  Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
4949  << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
4950  else if (ScopedEnumKWLoc.isValid())
4951  Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
4952  << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
4953  }
4954 
4955  stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4956 
4957  Sema::SkipBodyInfo SkipBody;
4958  if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4959  NextToken().is(tok::identifier))
4960  SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4961  NextToken().getIdentifierInfo(),
4962  NextToken().getLocation());
4963 
4964  bool Owned = false;
4965  bool IsDependent = false;
4966  const char *PrevSpec = nullptr;
4967  unsigned DiagID;
4968  Decl *TagDecl = Actions.ActOnTag(
4969  getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4970  attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4971  ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4972  DSC == DeclSpecContext::DSC_type_specifier,
4973  DSC == DeclSpecContext::DSC_template_param ||
4974  DSC == DeclSpecContext::DSC_template_type_arg,
4975  &SkipBody);
4976 
4977  if (SkipBody.ShouldSkip) {
4978  assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4979 
4980  BalancedDelimiterTracker T(*this, tok::l_brace);
4981  T.consumeOpen();
4982  T.skipToEnd();
4983 
4984  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4985  NameLoc.isValid() ? NameLoc : StartLoc,
4986  PrevSpec, DiagID, TagDecl, Owned,
4987  Actions.getASTContext().getPrintingPolicy()))
4988  Diag(StartLoc, DiagID) << PrevSpec;
4989  return;
4990  }
4991 
4992  if (IsDependent) {
4993  // This enum has a dependent nested-name-specifier. Handle it as a
4994  // dependent tag.
4995  if (!Name) {
4996  DS.SetTypeSpecError();
4997  Diag(Tok, diag::err_expected_type_name_after_typename);
4998  return;
4999  }
5000 
5001  TypeResult Type = Actions.ActOnDependentTag(
5002  getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
5003  if (Type.isInvalid()) {
5004  DS.SetTypeSpecError();
5005  return;
5006  }
5007 
5008  if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
5009  NameLoc.isValid() ? NameLoc : StartLoc,
5010  PrevSpec, DiagID, Type.get(),
5011  Actions.getASTContext().getPrintingPolicy()))
5012  Diag(StartLoc, DiagID) << PrevSpec;
5013 
5014  return;
5015  }
5016 
5017  if (!TagDecl) {
5018  // The action failed to produce an enumeration tag. If this is a
5019  // definition, consume the entire definition.
5020  if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
5021  ConsumeBrace();
5022  SkipUntil(tok::r_brace, StopAtSemi);
5023  }
5024 
5025  DS.SetTypeSpecError();
5026  return;
5027  }
5028 
5029  if (Tok.is(tok::l_brace) && TUK == Sema::TUK_Definition) {
5030  Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
5031  ParseEnumBody(StartLoc, D);
5032  if (SkipBody.CheckSameAsPrevious &&
5033  !Actions.ActOnDuplicateDefinition(TagDecl, SkipBody)) {
5034  DS.SetTypeSpecError();
5035  return;
5036  }
5037  }
5038 
5039  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
5040  NameLoc.isValid() ? NameLoc : StartLoc,
5041  PrevSpec, DiagID, TagDecl, Owned,
5042  Actions.getASTContext().getPrintingPolicy()))
5043  Diag(StartLoc, DiagID) << PrevSpec;
5044 }
5045 
5046 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
5047 /// enumerator-list:
5048 /// enumerator
5049 /// enumerator-list ',' enumerator
5050 /// enumerator:
5051 /// enumeration-constant attributes[opt]
5052 /// enumeration-constant attributes[opt] '=' constant-expression
5053 /// enumeration-constant:
5054 /// identifier
5055 ///
5056 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
5057  // Enter the scope of the enum body and start the definition.
5058  ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
5060 
5061  BalancedDelimiterTracker T(*this, tok::l_brace);
5062  T.consumeOpen();
5063 
5064  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
5065  if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
5066  Diag(Tok, diag::err_empty_enum);
5067 
5068  SmallVector<Decl *, 32> EnumConstantDecls;
5069  SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
5070 
5071  Decl *LastEnumConstDecl = nullptr;
5072 
5073  // Parse the enumerator-list.
5074  while (Tok.isNot(tok::r_brace)) {
5075  // Parse enumerator. If failed, try skipping till the start of the next
5076  // enumerator definition.
5077  if (Tok.isNot(tok::identifier)) {
5078  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
5079  if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
5080  TryConsumeToken(tok::comma))
5081  continue;
5082  break;
5083  }
5084  IdentifierInfo *Ident = Tok.getIdentifierInfo();
5085  SourceLocation IdentLoc = ConsumeToken();
5086 
5087  // If attributes exist after the enumerator, parse them.
5088  ParsedAttributes attrs(AttrFactory);
5089  MaybeParseGNUAttributes(attrs);
5090  if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
5091  if (getLangOpts().CPlusPlus)
5093  ? diag::warn_cxx14_compat_ns_enum_attribute
5094  : diag::ext_ns_enum_attribute)
5095  << 1 /*enumerator*/;
5096  ParseCXX11Attributes(attrs);
5097  }
5098 
5099  SourceLocation EqualLoc;
5100  ExprResult AssignedVal;
5101  EnumAvailabilityDiags.emplace_back(*this);
5102 
5103  EnterExpressionEvaluationContext ConstantEvaluated(
5105  if (TryConsumeToken(tok::equal, EqualLoc)) {
5107  if (AssignedVal.isInvalid())
5108  SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
5109  }
5110 
5111  // Install the enumerator constant into EnumDecl.
5112  Decl *EnumConstDecl = Actions.ActOnEnumConstant(
5113  getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
5114  EqualLoc, AssignedVal.get());
5115  EnumAvailabilityDiags.back().done();
5116 
5117  EnumConstantDecls.push_back(EnumConstDecl);
5118  LastEnumConstDecl = EnumConstDecl;
5119 
5120  if (Tok.is(tok::identifier)) {
5121  // We're missing a comma between enumerators.
5123  Diag(Loc, diag::err_enumerator_list_missing_comma)
5124  << FixItHint::CreateInsertion(Loc, ", ");
5125  continue;
5126  }
5127 
5128  // Emumerator definition must be finished, only comma or r_brace are
5129  // allowed here.
5130  SourceLocation CommaLoc;
5131  if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
5132  if (EqualLoc.isValid())
5133  Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
5134  << tok::comma;
5135  else
5136  Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
5137  if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
5138  if (TryConsumeToken(tok::comma, CommaLoc))
5139  continue;
5140  } else {
5141  break;
5142  }
5143  }
5144 
5145  // If comma is followed by r_brace, emit appropriate warning.
5146  if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
5147  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
5148  Diag(CommaLoc, getLangOpts().CPlusPlus ?
5149  diag::ext_enumerator_list_comma_cxx :
5150  diag::ext_enumerator_list_comma_c)
5151  << FixItHint::CreateRemoval(CommaLoc);
5152  else if (getLangOpts().CPlusPlus11)
5153  Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
5154  << FixItHint::CreateRemoval(CommaLoc);
5155  break;
5156  }
5157  }
5158 
5159  // Eat the }.
5160  T.consumeClose();
5161 
5162  // If attributes exist after the identifier list, parse them.
5163  ParsedAttributes attrs(AttrFactory);
5164  MaybeParseGNUAttributes(attrs);
5165 
5166  Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
5167  getCurScope(), attrs);
5168 
5169  // Now handle enum constant availability diagnostics.
5170  assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
5171  for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
5173  EnumAvailabilityDiags[i].redelay();
5174  PD.complete(EnumConstantDecls[i]);
5175  }
5176 
5177  EnumScope.Exit();
5178  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
5179 
5180  // The next token must be valid after an enum definition. If not, a ';'
5181  // was probably forgotten.
5182  bool CanBeBitfield = getCurScope()->isClassScope();
5183  if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
5184  ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
5185  // Push this token back into the preprocessor and change our current token
5186  // to ';' so that the rest of the code recovers as though there were an
5187  // ';' after the definition.
5188  PP.EnterToken(Tok, /*IsReinject=*/true);
5189  Tok.setKind(tok::semi);
5190  }
5191 }
5192 
5193 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
5194 /// is definitely a type-specifier. Return false if it isn't part of a type
5195 /// specifier or if we're not sure.
5196 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
5197  switch (Tok.getKind()) {
5198  default: return false;
5199  // type-specifiers
5200  case tok::kw_short:
5201  case tok::kw_long:
5202  case tok::kw___int64:
5203  case tok::kw___int128:
5204  case tok::kw_signed:
5205  case tok::kw_unsigned:
5206  case tok::kw__Complex:
5207  case tok::kw__Imaginary:
5208  case tok::kw_void:
5209  case tok::kw_char:
5210  case tok::kw_wchar_t:
5211  case tok::kw_char8_t:
5212  case tok::kw_char16_t:
5213  case tok::kw_char32_t:
5214  case tok::kw_int:
5215  case tok::kw__ExtInt:
5216  case tok::kw__BitInt:
5217  case tok::kw___bf16:
5218  case tok::kw_half:
5219  case tok::kw_float:
5220  case tok::kw_double:
5221  case tok::kw__Accum:
5222  case tok::kw__Fract:
5223  case tok::kw__Float16:
5224  case tok::kw___float128:
5225  case tok::kw___ibm128:
5226  case tok::kw_bool:
5227  case tok::kw__Bool:
5228  case tok::kw__Decimal32:
5229  case tok::kw__Decimal64:
5230  case tok::kw__Decimal128:
5231  case tok::kw___vector:
5232 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5233 #include "clang/Basic/OpenCLImageTypes.def"
5234 
5235  // struct-or-union-specifier (C99) or class-specifier (C++)
5236  case tok::kw_class:
5237  case tok::kw_struct:
5238  case tok::kw___interface:
5239  case tok::kw_union:
5240  // enum-specifier
5241  case tok::kw_enum:
5242 
5243  // typedef-name
5244  case tok::annot_typename:
5245  return true;
5246  }
5247 }
5248 
5249 /// isTypeSpecifierQualifier - Return true if the current token could be the
5250 /// start of a specifier-qualifier-list.
5251 bool Parser::isTypeSpecifierQualifier() {
5252  switch (Tok.getKind()) {
5253  default: return false;
5254 
5255  case tok::identifier: // foo::bar
5256  if (TryAltiVecVectorToken())
5257  return true;
5258  [[fallthrough]];
5259  case tok::kw_typename: // typename T::type
5260  // Annotate typenames and C++ scope specifiers. If we get one, just
5261  // recurse to handle whatever we get.
5263  return true;
5264  if (Tok.is(tok::identifier))
5265  return false;
5266  return isTypeSpecifierQualifier();
5267 
5268  case tok::coloncolon: // ::foo::bar
5269  if (NextToken().is(tok::kw_new) || // ::new
5270  NextToken().is(tok::kw_delete)) // ::delete
5271  return false;
5272 
5274  return true;
5275  return isTypeSpecifierQualifier();
5276 
5277  // GNU attributes support.
5278  case tok::kw___attribute:
5279  // C2x/GNU typeof support.
5280  case tok::kw_typeof:
5281  case tok::kw_typeof_unqual:
5282 
5283  // type-specifiers
5284  case tok::kw_short:
5285  case tok::kw_long:
5286  case tok::kw___int64:
5287  case tok::kw___int128:
5288  case tok::kw_signed:
5289  case tok::kw_unsigned:
5290  case tok::kw__Complex:
5291  case tok::kw__Imaginary:
5292  case tok::kw_void:
5293  case tok::kw_char:
5294  case tok::kw_wchar_t:
5295  case tok::kw_char8_t:
5296  case tok::kw_char16_t:
5297  case tok::kw_char32_t:
5298  case tok::kw_int:
5299  case tok::kw__ExtInt:
5300  case tok::kw__BitInt:
5301  case tok::kw_half:
5302  case tok::kw___bf16:
5303  case tok::kw_float:
5304  case tok::kw_double:
5305  case tok::kw__Accum:
5306  case tok::kw__Fract:
5307  case tok::kw__Float16:
5308  case tok::kw___float128:
5309  case tok::kw___ibm128:
5310  case tok::kw_bool:
5311  case tok::kw__Bool:
5312  case tok::kw__Decimal32:
5313  case tok::kw__Decimal64:
5314  case tok::kw__Decimal128:
5315  case tok::kw___vector:
5316 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5317 #include "clang/Basic/OpenCLImageTypes.def"
5318 
5319  // struct-or-union-specifier (C99) or class-specifier (C++)
5320  case tok::kw_class:
5321  case tok::kw_struct:
5322  case tok::kw___interface:
5323  case tok::kw_union:
5324  // enum-specifier
5325  case tok::kw_enum:
5326 
5327  // type-qualifier
5328  case tok::kw_const:
5329  case tok::kw_volatile:
5330  case tok::kw_restrict:
5331  case tok::kw__Sat:
5332 
5333  // Debugger support.
5334  case tok::kw___unknown_anytype:
5335 
5336  // typedef-name
5337  case tok::annot_typename:
5338  return true;
5339 
5340  // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5341  case tok::less:
5342  return getLangOpts().ObjC;
5343 
5344  case tok::kw___cdecl:
5345  case tok::kw___stdcall:
5346  case tok::kw___fastcall:
5347  case tok::kw___thiscall:
5348  case tok::kw___regcall:
5349  case tok::kw___vectorcall:
5350  case tok::kw___w64:
5351  case tok::kw___ptr64:
5352  case tok::kw___ptr32:
5353  case tok::kw___pascal:
5354  case tok::kw___unaligned:
5355 
5356  case tok::kw__Nonnull:
5357  case tok::kw__Nullable:
5358  case tok::kw__Nullable_result:
5359  case tok::kw__Null_unspecified:
5360 
5361  case tok::kw___kindof:
5362 
5363  case tok::kw___private:
5364  case tok::kw___local:
5365  case tok::kw___global:
5366  case tok::kw___constant:
5367  case tok::kw___generic:
5368  case tok::kw___read_only:
5369  case tok::kw___read_write:
5370  case tok::kw___write_only:
5371 
5372  case tok::kw_groupshared:
5373  return true;
5374 
5375  case tok::kw_private:
5376  return getLangOpts().OpenCL;
5377 
5378  // C11 _Atomic
5379  case tok::kw__Atomic:
5380  return true;
5381  }
5382 }
5383 
5384 /// isDeclarationSpecifier() - Return true if the current token is part of a
5385 /// declaration specifier.
5386 ///
5387 /// \param AllowImplicitTypename whether this is a context where T::type [T
5388 /// dependent] can appear.
5389 /// \param DisambiguatingWithExpression True to indicate that the purpose of
5390 /// this check is to disambiguate between an expression and a declaration.
5391 bool Parser::isDeclarationSpecifier(
5392  ImplicitTypenameContext AllowImplicitTypename,
5393  bool DisambiguatingWithExpression) {
5394  switch (Tok.getKind()) {
5395  default: return false;
5396 
5397  // OpenCL 2.0 and later define this keyword.
5398  case tok::kw_pipe:
5399  return getLangOpts().OpenCL &&
5401 
5402  case tok::identifier: // foo::bar
5403  // Unfortunate hack to support "Class.factoryMethod" notation.
5404  if (getLangOpts().ObjC && NextToken().is(tok::period))
5405  return false;
5406  if (TryAltiVecVectorToken())
5407  return true;
5408  [[fallthrough]];
5409  case tok::kw_decltype: // decltype(T())::type
5410  case tok::kw_typename: // typename T::type
5411  // Annotate typenames and C++ scope specifiers. If we get one, just
5412  // recurse to handle whatever we get.
5413  if (TryAnnotateTypeOrScopeToken(AllowImplicitTypename))
5414  return true;
5415  if (TryAnnotateTypeConstraint())
5416  return true;
5417  if (Tok.is(tok::identifier))
5418  return false;
5419 
5420  // If we're in Objective-C and we have an Objective-C class type followed
5421  // by an identifier and then either ':' or ']', in a place where an
5422  // expression is permitted, then this is probably a class message send
5423  // missing the initial '['. In this case, we won't consider this to be
5424  // the start of a declaration.
5425  if (DisambiguatingWithExpression &&
5426  isStartOfObjCClassMessageMissingOpenBracket())
5427  return false;
5428 
5429  return isDeclarationSpecifier(AllowImplicitTypename);
5430 
5431  case tok::coloncolon: // ::foo::bar
5432  if (!getLangOpts().CPlusPlus)
5433  return false;
5434  if (NextToken().is(tok::kw_new) || // ::new
5435  NextToken().is(tok::kw_delete)) // ::delete
5436  return false;
5437 
5438  // Annotate typenames and C++ scope specifiers. If we get one, just
5439  // recurse to handle whatever we get.
5441  return true;
5442  return isDeclarationSpecifier(ImplicitTypenameContext::No);
5443 
5444  // storage-class-specifier
5445  case tok::kw_typedef:
5446  case tok::kw_extern:
5447  case tok::kw___private_extern__:
5448  case tok::kw_static:
5449  case tok::kw_auto:
5450  case tok::kw___auto_type:
5451  case tok::kw_register:
5452  case tok::kw___thread:
5453  case tok::kw_thread_local:
5454  case tok::kw__Thread_local:
5455 
5456  // Modules
5457  case tok::kw___module_private__:
5458 
5459  // Debugger support
5460  case tok::kw___unknown_anytype:
5461 
5462  // type-specifiers
5463  case tok::kw_short:
5464  case tok::kw_long:
5465  case tok::kw___int64:
5466  case tok::kw___int128:
5467  case tok::kw_signed:
5468  case tok::kw_unsigned:
5469  case tok::kw__Complex:
5470  case tok::kw__Imaginary:
5471  case tok::kw_void:
5472  case tok::kw_char:
5473  case tok::kw_wchar_t:
5474  case tok::kw_char8_t:
5475  case tok::kw_char16_t:
5476  case tok::kw_char32_t:
5477 
5478  case tok::kw_int:
5479  case tok::kw__ExtInt:
5480  case tok::kw__BitInt:
5481  case tok::kw_half:
5482  case tok::kw___bf16:
5483  case tok::kw_float:
5484  case tok::kw_double:
5485  case tok::kw__Accum:
5486  case tok::kw__Fract:
5487  case tok::kw__Float16:
5488  case tok::kw___float128:
5489  case tok::kw___ibm128:
5490  case tok::kw_bool:
5491  case tok::kw__Bool:
5492  case tok::kw__Decimal32:
5493  case tok::kw__Decimal64:
5494  case tok::kw__Decimal128:
5495  case tok::kw___vector:
5496 
5497  // struct-or-union-specifier (C99) or class-specifier (C++)
5498  case tok::kw_class:
5499  case tok::kw_struct:
5500  case tok::kw_union:
5501  case tok::kw___interface:
5502  // enum-specifier
5503  case tok::kw_enum:
5504 
5505  // type-qualifier
5506  case tok::kw_const:
5507  case tok::kw_volatile:
5508  case tok::kw_restrict:
5509  case tok::kw__Sat:
5510 
5511  // function-specifier
5512  case tok::kw_inline:
5513  case tok::kw_virtual:
5514  case tok::kw_explicit:
5515  case tok::kw__Noreturn:
5516 
5517  // alignment-specifier
5518  case tok::kw__Alignas:
5519 
5520  // friend keyword.
5521  case tok::kw_friend:
5522 
5523  // static_assert-declaration
5524  case tok::kw_static_assert:
5525  case tok::kw__Static_assert:
5526 
5527  // C2x/GNU typeof support.
5528  case tok::kw_typeof:
5529  case tok::kw_typeof_unqual:
5530 
5531  // GNU attributes.
5532  case tok::kw___attribute:
5533 
5534  // C++11 decltype and constexpr.
5535  case tok::annot_decltype:
5536  case tok::kw_constexpr:
5537 
5538  // C++20 consteval and constinit.
5539  case tok::kw_consteval:
5540  case tok::kw_constinit:
5541 
5542  // C11 _Atomic
5543  case tok::kw__Atomic:
5544  return true;
5545 
5546  // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5547  case tok::less:
5548  return getLangOpts().ObjC;
5549 
5550  // typedef-name
5551  case tok::annot_typename:
5552  return !DisambiguatingWithExpression ||
5553  !isStartOfObjCClassMessageMissingOpenBracket();
5554 
5555  // placeholder-type-specifier
5556  case tok::annot_template_id: {
5557  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
5558  if (TemplateId->hasInvalidName())
5559  return true;
5560  // FIXME: What about type templates that have only been annotated as
5561  // annot_template_id, not as annot_typename?
5562  return isTypeConstraintAnnotation() &&
5563  (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
5564  }
5565 
5566  case tok::annot_cxxscope: {
5567  TemplateIdAnnotation *TemplateId =
5568  NextToken().is(tok::annot_template_id)
5569  ? takeTemplateIdAnnotation(NextToken())
5570  : nullptr;
5571  if (TemplateId && TemplateId->hasInvalidName())
5572  return true;
5573  // FIXME: What about type templates that have only been annotated as
5574  // annot_template_id, not as annot_typename?
5575  if (NextToken().is(tok::identifier) && TryAnnotateTypeConstraint())
5576  return true;
5577  return isTypeConstraintAnnotation() &&
5578  GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype);
5579  }
5580 
5581  case tok::kw___declspec:
5582  case tok::kw___cdecl:
5583  case tok::kw___stdcall:
5584  case tok::kw___fastcall:
5585  case tok::kw___thiscall:
5586  case tok::kw___regcall:
5587  case tok::kw___vectorcall:
5588  case tok::kw___w64:
5589  case tok::kw___sptr:
5590  case tok::kw___uptr:
5591  case tok::kw___ptr64:
5592  case tok::kw___ptr32:
5593  case tok::kw___forceinline:
5594  case tok::kw___pascal:
5595  case tok::kw___unaligned:
5596 
5597  case tok::kw__Nonnull:
5598  case tok::kw__Nullable:
5599  case tok::kw__Nullable_result:
5600  case tok::kw__Null_unspecified:
5601 
5602  case tok::kw___kindof:
5603 
5604  case tok::kw___private:
5605  case tok::kw___local:
5606  case tok::kw___global:
5607  case tok::kw___constant:
5608  case tok::kw___generic:
5609  case tok::kw___read_only:
5610  case tok::kw___read_write:
5611  case tok::kw___write_only:
5612 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5613 #include "clang/Basic/OpenCLImageTypes.def"
5614 
5615  case tok::kw_groupshared:
5616  return true;
5617 
5618  case tok::kw_private:
5619  return getLangOpts().OpenCL;
5620  }
5621 }
5622 
5623 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide,
5624  DeclSpec::FriendSpecified IsFriend) {
5625  TentativeParsingAction TPA(*this);
5626 
5627  // Parse the C++ scope specifier.
5628  CXXScopeSpec SS;
5629  if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
5630  /*ObjectHasErrors=*/false,
5631  /*EnteringContext=*/true)) {
5632  TPA.Revert();
5633  return false;
5634  }
5635 
5636  // Parse the constructor name.
5637  if (Tok.is(tok::identifier)) {
5638  // We already know that we have a constructor name; just consume
5639  // the token.
5640  ConsumeToken();
5641  } else if (Tok.is(tok::annot_template_id)) {
5642  ConsumeAnnotationToken();
5643  } else {
5644  TPA.Revert();
5645  return false;
5646  }
5647 
5648  // There may be attributes here, appertaining to the constructor name or type
5649  // we just stepped past.
5650  SkipCXX11Attributes();
5651 
5652  // Current class name must be followed by a left parenthesis.
5653  if (Tok.isNot(tok::l_paren)) {
5654  TPA.Revert();
5655  return false;
5656  }
5657  ConsumeParen();
5658 
5659  // A right parenthesis, or ellipsis followed by a right parenthesis signals
5660  // that we have a constructor.
5661  if (Tok.is(tok::r_paren) ||
5662  (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5663  TPA.Revert();
5664  return true;
5665  }
5666 
5667  // A C++11 attribute here signals that we have a constructor, and is an
5668  // attribute on the first constructor parameter.
5669  if (getLangOpts().CPlusPlus11 &&
5670  isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5671  /*OuterMightBeMessageSend*/ true)) {
5672  TPA.Revert();
5673  return true;
5674  }
5675 
5676  // If we need to, enter the specified scope.
5677  DeclaratorScopeObj DeclScopeObj(*this, SS);
5678  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5679  DeclScopeObj.EnterDeclaratorScope();
5680 
5681  // Optionally skip Microsoft attributes.
5682  ParsedAttributes Attrs(AttrFactory);
5683  MaybeParseMicrosoftAttributes(Attrs);
5684 
5685  // Check whether the next token(s) are part of a declaration
5686  // specifier, in which case we have the start of a parameter and,
5687  // therefore, we know that this is a constructor.
5688  // Due to an ambiguity with implicit typename, the above is not enough.
5689  // Additionally, check to see if we are a friend.
5690  bool IsConstructor = false;
5691  if (isDeclarationSpecifier(IsFriend ? ImplicitTypenameContext::No
5693  IsConstructor = true;
5694  else if (Tok.is(tok::identifier) ||
5695  (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5696  // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5697  // This might be a parenthesized member name, but is more likely to
5698  // be a constructor declaration with an invalid argument type. Keep
5699  // looking.
5700  if (Tok.is(tok::annot_cxxscope))
5701  ConsumeAnnotationToken();
5702  ConsumeToken();
5703 
5704  // If this is not a constructor, we must be parsing a declarator,
5705  // which must have one of the following syntactic forms (see the
5706  // grammar extract at the start of ParseDirectDeclarator):
5707  switch (Tok.getKind()) {
5708  case tok::l_paren:
5709  // C(X ( int));
5710  case tok::l_square:
5711  // C(X [ 5]);
5712  // C(X [ [attribute]]);
5713  case tok::coloncolon:
5714  // C(X :: Y);
5715  // C(X :: *p);
5716  // Assume this isn't a constructor, rather than assuming it's a
5717  // constructor with an unnamed parameter of an ill-formed type.
5718  break;
5719 
5720  case tok::r_paren:
5721  // C(X )
5722 
5723  // Skip past the right-paren and any following attributes to get to
5724  // the function body or trailing-return-type.
5725  ConsumeParen();
5726  SkipCXX11Attributes();
5727 
5728  if (DeductionGuide) {
5729  // C(X) -> ... is a deduction guide.
5730  IsConstructor = Tok.is(tok::arrow);
5731  break;
5732  }
5733  if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5734  // Assume these were meant to be constructors:
5735  // C(X) : (the name of a bit-field cannot be parenthesized).
5736  // C(X) try (this is otherwise ill-formed).
5737  IsConstructor = true;
5738  }
5739  if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5740  // If we have a constructor name within the class definition,
5741  // assume these were meant to be constructors:
5742  // C(X) {
5743  // C(X) ;
5744  // ... because otherwise we would be declaring a non-static data
5745  // member that is ill-formed because it's of the same type as its
5746  // surrounding class.
5747  //
5748  // FIXME: We can actually do this whether or not the name is qualified,
5749  // because if it is qualified in this context it must be being used as
5750  // a constructor name.
5751  // currently, so we're somewhat conservative here.
5752  IsConstructor = IsUnqualified;
5753  }
5754  break;
5755 
5756  default:
5757  IsConstructor = true;
5758  break;
5759  }
5760  }
5761 
5762  TPA.Revert();
5763  return IsConstructor;
5764 }
5765 
5766 /// ParseTypeQualifierListOpt
5767 /// type-qualifier-list: [C99 6.7.5]
5768 /// type-qualifier
5769 /// [vendor] attributes
5770 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5771 /// type-qualifier-list type-qualifier
5772 /// [vendor] type-qualifier-list attributes
5773 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5774 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5775 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5776 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5777 /// AttrRequirements bitmask values.
5778 void Parser::ParseTypeQualifierListOpt(
5779  DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5780  bool IdentifierRequired,
5781  Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5782  if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5783  isCXX11AttributeSpecifier()) {
5784  ParsedAttributes Attrs(AttrFactory);
5785  ParseCXX11Attributes(Attrs);
5786  DS.takeAttributesFrom(Attrs);
5787  }
5788 
5789  SourceLocation EndLoc;
5790 
5791  while (true) {
5792  bool isInvalid = false;
5793  const char *PrevSpec = nullptr;
5794  unsigned DiagID = 0;
5795  SourceLocation Loc = Tok.getLocation();
5796 
5797  switch (Tok.getKind()) {
5798  case tok::code_completion:
5799  cutOffParsing();
5801  (*CodeCompletionHandler)();
5802  else
5803  Actions.CodeCompleteTypeQualifiers(DS);
5804  return;
5805 
5806  case tok::kw_const:
5807  isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5808  getLangOpts());
5809  break;
5810  case tok::kw_volatile:
5811  isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5812  getLangOpts());
5813  break;
5814  case tok::kw_restrict:
5815  isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5816  getLangOpts());
5817  break;
5818  case tok::kw__Atomic:
5819  if (!AtomicAllowed)
5820  goto DoneWithTypeQuals;
5821  if (!getLangOpts().C11)
5822  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
5823  isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5824  getLangOpts());
5825  break;
5826 
5827  // OpenCL qualifiers:
5828  case tok::kw_private:
5829  if (!getLangOpts().OpenCL)
5830  goto DoneWithTypeQuals;
5831  [[fallthrough]];
5832  case tok::kw___private:
5833  case tok::kw___global:
5834  case tok::kw___local:
5835  case tok::kw___constant:
5836  case tok::kw___generic:
5837  case tok::kw___read_only:
5838  case tok::kw___write_only:
5839  case tok::kw___read_write:
5840  ParseOpenCLQualifiers(DS.getAttributes());
5841  break;
5842 
5843  case tok::kw_groupshared:
5844  // NOTE: ParseHLSLQualifiers will consume the qualifier token.
5845  ParseHLSLQualifiers(DS.getAttributes());
5846  continue;
5847 
5848  case tok::kw___unaligned: