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