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