clang  10.0.0svn
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;
1298  ParseStringLiteralExpression();
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;
1307  ParseStringLiteralExpression();
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 // Late Parsed Attributes:
1413 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1414 
1415 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1416 
1417 void Parser::LateParsedClass::ParseLexedAttributes() {
1418  Self->ParseLexedAttributes(*Class);
1419 }
1420 
1421 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1422  Self->ParseLexedAttribute(*this, true, false);
1423 }
1424 
1425 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1426 /// scope appropriately.
1427 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1428  // Deal with templates
1429  // FIXME: Test cases to make sure this does the right thing for templates.
1430  bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1431  ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1432  HasTemplateScope);
1433  if (HasTemplateScope)
1434  Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1435 
1436  // Set or update the scope flags.
1437  bool AlreadyHasClassScope = Class.TopLevelClass;
1438  unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1439  ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1440  ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1441 
1442  // Enter the scope of nested classes
1443  if (!AlreadyHasClassScope)
1445  Class.TagOrTemplate);
1446  if (!Class.LateParsedDeclarations.empty()) {
1447  for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1448  Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1449  }
1450  }
1451 
1452  if (!AlreadyHasClassScope)
1454  Class.TagOrTemplate);
1455 }
1456 
1457 /// Parse all attributes in LAs, and attach them to Decl D.
1458 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1459  bool EnterScope, bool OnDefinition) {
1460  assert(LAs.parseSoon() &&
1461  "Attribute list should be marked for immediate parsing.");
1462  for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1463  if (D)
1464  LAs[i]->addDecl(D);
1465  ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1466  delete LAs[i];
1467  }
1468  LAs.clear();
1469 }
1470 
1471 /// Finish parsing an attribute for which parsing was delayed.
1472 /// This will be called at the end of parsing a class declaration
1473 /// for each LateParsedAttribute. We consume the saved tokens and
1474 /// create an attribute with the arguments filled in. We add this
1475 /// to the Attribute list for the decl.
1476 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1477  bool EnterScope, bool OnDefinition) {
1478  // Create a fake EOF so that attribute parsing won't go off the end of the
1479  // attribute.
1480  Token AttrEnd;
1481  AttrEnd.startToken();
1482  AttrEnd.setKind(tok::eof);
1483  AttrEnd.setLocation(Tok.getLocation());
1484  AttrEnd.setEofData(LA.Toks.data());
1485  LA.Toks.push_back(AttrEnd);
1486 
1487  // Append the current token at the end of the new token stream so that it
1488  // doesn't get lost.
1489  LA.Toks.push_back(Tok);
1490  PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
1491  // Consume the previously pushed token.
1492  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1493 
1494  ParsedAttributes Attrs(AttrFactory);
1495  SourceLocation endLoc;
1496 
1497  if (LA.Decls.size() > 0) {
1498  Decl *D = LA.Decls[0];
1499  NamedDecl *ND = dyn_cast<NamedDecl>(D);
1500  RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1501 
1502  // Allow 'this' within late-parsed attributes.
1503  Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
1504  ND && ND->isCXXInstanceMember());
1505 
1506  if (LA.Decls.size() == 1) {
1507  // If the Decl is templatized, add template parameters to scope.
1508  bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1509  ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1510  if (HasTemplateScope)
1511  Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1512 
1513  // If the Decl is on a function, add function parameters to the scope.
1514  bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1515  ParseScope FnScope(
1517  HasFunScope);
1518  if (HasFunScope)
1519  Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1520 
1521  ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1522  nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1523  nullptr);
1524 
1525  if (HasFunScope) {
1526  Actions.ActOnExitFunctionContext();
1527  FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
1528  }
1529  if (HasTemplateScope) {
1530  TempScope.Exit();
1531  }
1532  } else {
1533  // If there are multiple decls, then the decl cannot be within the
1534  // function scope.
1535  ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1536  nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1537  nullptr);
1538  }
1539  } else {
1540  Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1541  }
1542 
1543  if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1544  Attrs.begin()->isKnownToGCC())
1545  Diag(Tok, diag::warn_attribute_on_function_definition)
1546  << &LA.AttrName;
1547 
1548  for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1549  Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1550 
1551  // Due to a parsing error, we either went over the cached tokens or
1552  // there are still cached tokens left, so we skip the leftover tokens.
1553  while (Tok.isNot(tok::eof))
1554  ConsumeAnyToken();
1555 
1556  if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1557  ConsumeAnyToken();
1558 }
1559 
1560 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1561  SourceLocation AttrNameLoc,
1562  ParsedAttributes &Attrs,
1563  SourceLocation *EndLoc,
1564  IdentifierInfo *ScopeName,
1565  SourceLocation ScopeLoc,
1566  ParsedAttr::Syntax Syntax) {
1567  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1568 
1569  BalancedDelimiterTracker T(*this, tok::l_paren);
1570  T.consumeOpen();
1571 
1572  if (Tok.isNot(tok::identifier)) {
1573  Diag(Tok, diag::err_expected) << tok::identifier;
1574  T.skipToEnd();
1575  return;
1576  }
1577  IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1578 
1579  if (ExpectAndConsume(tok::comma)) {
1580  T.skipToEnd();
1581  return;
1582  }
1583 
1584  SourceRange MatchingCTypeRange;
1585  TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1586  if (MatchingCType.isInvalid()) {
1587  T.skipToEnd();
1588  return;
1589  }
1590 
1591  bool LayoutCompatible = false;
1592  bool MustBeNull = false;
1593  while (TryConsumeToken(tok::comma)) {
1594  if (Tok.isNot(tok::identifier)) {
1595  Diag(Tok, diag::err_expected) << tok::identifier;
1596  T.skipToEnd();
1597  return;
1598  }
1599  IdentifierInfo *Flag = Tok.getIdentifierInfo();
1600  if (Flag->isStr("layout_compatible"))
1601  LayoutCompatible = true;
1602  else if (Flag->isStr("must_be_null"))
1603  MustBeNull = true;
1604  else {
1605  Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1606  T.skipToEnd();
1607  return;
1608  }
1609  ConsumeToken(); // consume flag
1610  }
1611 
1612  if (!T.consumeClose()) {
1613  Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1614  ArgumentKind, MatchingCType.get(),
1615  LayoutCompatible, MustBeNull, Syntax);
1616  }
1617 
1618  if (EndLoc)
1619  *EndLoc = T.getCloseLocation();
1620 }
1621 
1622 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1623 /// of a C++11 attribute-specifier in a location where an attribute is not
1624 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1625 /// situation.
1626 ///
1627 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1628 /// this doesn't appear to actually be an attribute-specifier, and the caller
1629 /// should try to parse it.
1630 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1631  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1632 
1633  switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1634  case CAK_NotAttributeSpecifier:
1635  // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1636  return false;
1637 
1638  case CAK_InvalidAttributeSpecifier:
1639  Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1640  return false;
1641 
1642  case CAK_AttributeSpecifier:
1643  // Parse and discard the attributes.
1644  SourceLocation BeginLoc = ConsumeBracket();
1645  ConsumeBracket();
1646  SkipUntil(tok::r_square);
1647  assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1648  SourceLocation EndLoc = ConsumeBracket();
1649  Diag(BeginLoc, diag::err_attributes_not_allowed)
1650  << SourceRange(BeginLoc, EndLoc);
1651  return true;
1652  }
1653  llvm_unreachable("All cases handled above.");
1654 }
1655 
1656 /// We have found the opening square brackets of a C++11
1657 /// attribute-specifier in a location where an attribute is not permitted, but
1658 /// we know where the attributes ought to be written. Parse them anyway, and
1659 /// provide a fixit moving them to the right place.
1660 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1661  SourceLocation CorrectLocation) {
1662  assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1663  Tok.is(tok::kw_alignas));
1664 
1665  // Consume the attributes.
1666  SourceLocation Loc = Tok.getLocation();
1667  ParseCXX11Attributes(Attrs);
1668  CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1669  // FIXME: use err_attributes_misplaced
1670  Diag(Loc, diag::err_attributes_not_allowed)
1671  << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1672  << FixItHint::CreateRemoval(AttrRange);
1673 }
1674 
1675 void Parser::DiagnoseProhibitedAttributes(
1676  const SourceRange &Range, const SourceLocation CorrectLocation) {
1677  if (CorrectLocation.isValid()) {
1678  CharSourceRange AttrRange(Range, true);
1679  Diag(CorrectLocation, diag::err_attributes_misplaced)
1680  << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1681  << FixItHint::CreateRemoval(AttrRange);
1682  } else
1683  Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1684 }
1685 
1686 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1687  unsigned DiagID) {
1688  for (const ParsedAttr &AL : Attrs) {
1689  if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1690  continue;
1691  if (AL.getKind() == ParsedAttr::UnknownAttribute)
1692  Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
1693  else {
1694  Diag(AL.getLoc(), DiagID) << AL;
1695  AL.setInvalid();
1696  }
1697  }
1698 }
1699 
1700 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1701 // applies to var, not the type Foo.
1702 // As an exception to the rule, __declspec(align(...)) before the
1703 // class-key affects the type instead of the variable.
1704 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1705 // variable.
1706 // This function moves attributes that should apply to the type off DS to Attrs.
1707 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1708  DeclSpec &DS,
1709  Sema::TagUseKind TUK) {
1710  if (TUK == Sema::TUK_Reference)
1711  return;
1712 
1714 
1715  for (ParsedAttr &AL : DS.getAttributes()) {
1716  if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1717  AL.isDeclspecAttribute()) ||
1718  AL.isMicrosoftAttribute())
1719  ToBeMoved.push_back(&AL);
1720  }
1721 
1722  for (ParsedAttr *AL : ToBeMoved) {
1723  DS.getAttributes().remove(AL);
1724  Attrs.addAtEnd(AL);
1725  }
1726 }
1727 
1728 /// ParseDeclaration - Parse a full 'declaration', which consists of
1729 /// declaration-specifiers, some number of declarators, and a semicolon.
1730 /// 'Context' should be a DeclaratorContext value. This returns the
1731 /// location of the semicolon in DeclEnd.
1732 ///
1733 /// declaration: [C99 6.7]
1734 /// block-declaration ->
1735 /// simple-declaration
1736 /// others [FIXME]
1737 /// [C++] template-declaration
1738 /// [C++] namespace-definition
1739 /// [C++] using-directive
1740 /// [C++] using-declaration
1741 /// [C++11/C11] static_assert-declaration
1742 /// others... [FIXME]
1743 ///
1745 Parser::ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1746  ParsedAttributesWithRange &attrs,
1747  SourceLocation *DeclSpecStart) {
1748  ParenBraceBracketBalancer BalancerRAIIObj(*this);
1749  // Must temporarily exit the objective-c container scope for
1750  // parsing c none objective-c decls.
1751  ObjCDeclContextSwitch ObjCDC(*this);
1752 
1753  Decl *SingleDecl = nullptr;
1754  switch (Tok.getKind()) {
1755  case tok::kw_template:
1756  case tok::kw_export:
1757  ProhibitAttributes(attrs);
1758  SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1759  break;
1760  case tok::kw_inline:
1761  // Could be the start of an inline namespace. Allowed as an ext in C++03.
1762  if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1763  ProhibitAttributes(attrs);
1764  SourceLocation InlineLoc = ConsumeToken();
1765  return ParseNamespace(Context, DeclEnd, InlineLoc);
1766  }
1767  return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1768  DeclSpecStart);
1769  case tok::kw_namespace:
1770  ProhibitAttributes(attrs);
1771  return ParseNamespace(Context, DeclEnd);
1772  case tok::kw_using:
1773  return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1774  DeclEnd, attrs);
1775  case tok::kw_static_assert:
1776  case tok::kw__Static_assert:
1777  ProhibitAttributes(attrs);
1778  SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1779  break;
1780  default:
1781  return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1782  DeclSpecStart);
1783  }
1784 
1785  // This routine returns a DeclGroup, if the thing we parsed only contains a
1786  // single decl, convert it now.
1787  return Actions.ConvertDeclToDeclGroup(SingleDecl);
1788 }
1789 
1790 /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1791 /// declaration-specifiers init-declarator-list[opt] ';'
1792 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1793 /// init-declarator-list ';'
1794 ///[C90/C++]init-declarator-list ';' [TODO]
1795 /// [OMP] threadprivate-directive
1796 /// [OMP] allocate-directive [TODO]
1797 ///
1798 /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
1799 /// attribute-specifier-seq[opt] type-specifier-seq declarator
1800 ///
1801 /// If RequireSemi is false, this does not check for a ';' at the end of the
1802 /// declaration. If it is true, it checks for and eats it.
1803 ///
1804 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1805 /// of a simple-declaration. If we find that we are, we also parse the
1806 /// for-range-initializer, and place it here.
1807 ///
1808 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1809 /// the Declaration. The SourceLocation for this Decl is set to
1810 /// DeclSpecStart if DeclSpecStart is non-null.
1811 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1812  DeclaratorContext Context, SourceLocation &DeclEnd,
1813  ParsedAttributesWithRange &Attrs, bool RequireSemi, ForRangeInit *FRI,
1814  SourceLocation *DeclSpecStart) {
1815  // Parse the common declaration-specifiers piece.
1816  ParsingDeclSpec DS(*this);
1817 
1818  DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1819  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1820 
1821  // If we had a free-standing type definition with a missing semicolon, we
1822  // may get this far before the problem becomes obvious.
1823  if (DS.hasTagDefinition() &&
1824  DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1825  return nullptr;
1826 
1827  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1828  // declaration-specifiers init-declarator-list[opt] ';'
1829  if (Tok.is(tok::semi)) {
1830  ProhibitAttributes(Attrs);
1831  DeclEnd = Tok.getLocation();
1832  if (RequireSemi) ConsumeToken();
1833  RecordDecl *AnonRecord = nullptr;
1834  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1835  DS, AnonRecord);
1836  DS.complete(TheDecl);
1837  if (AnonRecord) {
1838  Decl* decls[] = {AnonRecord, TheDecl};
1839  return Actions.BuildDeclaratorGroup(decls);
1840  }
1841  return Actions.ConvertDeclToDeclGroup(TheDecl);
1842  }
1843 
1844  if (DeclSpecStart)
1845  DS.SetRangeStart(*DeclSpecStart);
1846 
1847  DS.takeAttributesFrom(Attrs);
1848  return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1849 }
1850 
1851 /// Returns true if this might be the start of a declarator, or a common typo
1852 /// for a declarator.
1853 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1854  switch (Tok.getKind()) {
1855  case tok::annot_cxxscope:
1856  case tok::annot_template_id:
1857  case tok::caret:
1858  case tok::code_completion:
1859  case tok::coloncolon:
1860  case tok::ellipsis:
1861  case tok::kw___attribute:
1862  case tok::kw_operator:
1863  case tok::l_paren:
1864  case tok::star:
1865  return true;
1866 
1867  case tok::amp:
1868  case tok::ampamp:
1869  return getLangOpts().CPlusPlus;
1870 
1871  case tok::l_square: // Might be an attribute on an unnamed bit-field.
1872  return Context == DeclaratorContext::MemberContext &&
1873  getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1874 
1875  case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1876  return Context == DeclaratorContext::MemberContext ||
1877  getLangOpts().CPlusPlus;
1878 
1879  case tok::identifier:
1880  switch (NextToken().getKind()) {
1881  case tok::code_completion:
1882  case tok::coloncolon:
1883  case tok::comma:
1884  case tok::equal:
1885  case tok::equalequal: // Might be a typo for '='.
1886  case tok::kw_alignas:
1887  case tok::kw_asm:
1888  case tok::kw___attribute:
1889  case tok::l_brace:
1890  case tok::l_paren:
1891  case tok::l_square:
1892  case tok::less:
1893  case tok::r_brace:
1894  case tok::r_paren:
1895  case tok::r_square:
1896  case tok::semi:
1897  return true;
1898 
1899  case tok::colon:
1900  // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1901  // and in block scope it's probably a label. Inside a class definition,
1902  // this is a bit-field.
1903  return Context == DeclaratorContext::MemberContext ||
1904  (getLangOpts().CPlusPlus &&
1905  Context == DeclaratorContext::FileContext);
1906 
1907  case tok::identifier: // Possible virt-specifier.
1908  return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1909 
1910  default:
1911  return false;
1912  }
1913 
1914  default:
1915  return false;
1916  }
1917 }
1918 
1919 /// Skip until we reach something which seems like a sensible place to pick
1920 /// up parsing after a malformed declaration. This will sometimes stop sooner
1921 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1923  while (true) {
1924  switch (Tok.getKind()) {
1925  case tok::l_brace:
1926  // Skip until matching }, then stop. We've probably skipped over
1927  // a malformed class or function definition or similar.
1928  ConsumeBrace();
1929  SkipUntil(tok::r_brace);
1930  if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1931  // This declaration isn't over yet. Keep skipping.
1932  continue;
1933  }
1934  TryConsumeToken(tok::semi);
1935  return;
1936 
1937  case tok::l_square:
1938  ConsumeBracket();
1939  SkipUntil(tok::r_square);
1940  continue;
1941 
1942  case tok::l_paren:
1943  ConsumeParen();
1944  SkipUntil(tok::r_paren);
1945  continue;
1946 
1947  case tok::r_brace:
1948  return;
1949 
1950  case tok::semi:
1951  ConsumeToken();
1952  return;
1953 
1954  case tok::kw_inline:
1955  // 'inline namespace' at the start of a line is almost certainly
1956  // a good place to pick back up parsing, except in an Objective-C
1957  // @interface context.
1958  if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1959  (!ParsingInObjCContainer || CurParsedObjCImpl))
1960  return;
1961  break;
1962 
1963  case tok::kw_namespace:
1964  // 'namespace' at the start of a line is almost certainly a good
1965  // place to pick back up parsing, except in an Objective-C
1966  // @interface context.
1967  if (Tok.isAtStartOfLine() &&
1968  (!ParsingInObjCContainer || CurParsedObjCImpl))
1969  return;
1970  break;
1971 
1972  case tok::at:
1973  // @end is very much like } in Objective-C contexts.
1974  if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1975  ParsingInObjCContainer)
1976  return;
1977  break;
1978 
1979  case tok::minus:
1980  case tok::plus:
1981  // - and + probably start new method declarations in Objective-C contexts.
1982  if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1983  return;
1984  break;
1985 
1986  case tok::eof:
1987  case tok::annot_module_begin:
1988  case tok::annot_module_end:
1989  case tok::annot_module_include:
1990  return;
1991 
1992  default:
1993  break;
1994  }
1995 
1996  ConsumeAnyToken();
1997  }
1998 }
1999 
2000 /// ParseDeclGroup - Having concluded that this is either a function
2001 /// definition or a group of object declarations, actually parse the
2002 /// result.
2003 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2004  DeclaratorContext Context,
2005  SourceLocation *DeclEnd,
2006  ForRangeInit *FRI) {
2007  // Parse the first declarator.
2008  ParsingDeclarator D(*this, DS, Context);
2009  ParseDeclarator(D);
2010 
2011  // Bail out if the first declarator didn't seem well-formed.
2012  if (!D.hasName() && !D.mayOmitIdentifier()) {
2014  return nullptr;
2015  }
2016 
2017  // Save late-parsed attributes for now; they need to be parsed in the
2018  // appropriate function scope after the function Decl has been constructed.
2019  // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2020  LateParsedAttrList LateParsedAttrs(true);
2021  if (D.isFunctionDeclarator()) {
2022  MaybeParseGNUAttributes(D, &LateParsedAttrs);
2023 
2024  // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2025  // attribute. If we find the keyword here, tell the user to put it
2026  // at the start instead.
2027  if (Tok.is(tok::kw__Noreturn)) {
2028  SourceLocation Loc = ConsumeToken();
2029  const char *PrevSpec;
2030  unsigned DiagID;
2031 
2032  // We can offer a fixit if it's valid to mark this function as _Noreturn
2033  // and we don't have any other declarators in this declaration.
2034  bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2035  MaybeParseGNUAttributes(D, &LateParsedAttrs);
2036  Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2037 
2038  Diag(Loc, diag::err_c11_noreturn_misplaced)
2039  << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2040  << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2041  : FixItHint());
2042  }
2043  }
2044 
2045  // Check to see if we have a function *definition* which must have a body.
2046  if (D.isFunctionDeclarator() &&
2047  // Look at the next token to make sure that this isn't a function
2048  // declaration. We have to check this because __attribute__ might be the
2049  // start of a function definition in GCC-extended K&R C.
2050  !isDeclarationAfterDeclarator()) {
2051 
2052  // Function definitions are only allowed at file scope and in C++ classes.
2053  // The C++ inline method definition case is handled elsewhere, so we only
2054  // need to handle the file scope definition case.
2055  if (Context == DeclaratorContext::FileContext) {
2056  if (isStartOfFunctionDefinition(D)) {
2058  Diag(Tok, diag::err_function_declared_typedef);
2059 
2060  // Recover by treating the 'typedef' as spurious.
2062  }
2063 
2064  Decl *TheDecl =
2065  ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2066  return Actions.ConvertDeclToDeclGroup(TheDecl);
2067  }
2068 
2069  if (isDeclarationSpecifier()) {
2070  // If there is an invalid declaration specifier right after the
2071  // function prototype, then we must be in a missing semicolon case
2072  // where this isn't actually a body. Just fall through into the code
2073  // that handles it as a prototype, and let the top-level code handle
2074  // the erroneous declspec where it would otherwise expect a comma or
2075  // semicolon.
2076  } else {
2077  Diag(Tok, diag::err_expected_fn_body);
2078  SkipUntil(tok::semi);
2079  return nullptr;
2080  }
2081  } else {
2082  if (Tok.is(tok::l_brace)) {
2083  Diag(Tok, diag::err_function_definition_not_allowed);
2085  return nullptr;
2086  }
2087  }
2088  }
2089 
2090  if (ParseAsmAttributesAfterDeclarator(D))
2091  return nullptr;
2092 
2093  // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2094  // must parse and analyze the for-range-initializer before the declaration is
2095  // analyzed.
2096  //
2097  // Handle the Objective-C for-in loop variable similarly, although we
2098  // don't need to parse the container in advance.
2099  if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2100  bool IsForRangeLoop = false;
2101  if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2102  IsForRangeLoop = true;
2103  if (Tok.is(tok::l_brace))
2104  FRI->RangeExpr = ParseBraceInitializer();
2105  else
2106  FRI->RangeExpr = ParseExpression();
2107  }
2108 
2109  Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2110  if (IsForRangeLoop) {
2111  Actions.ActOnCXXForRangeDecl(ThisDecl);
2112  } else {
2113  // Obj-C for loop
2114  if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2115  VD->setObjCForDecl(true);
2116  }
2117  Actions.FinalizeDeclaration(ThisDecl);
2118  D.complete(ThisDecl);
2119  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2120  }
2121 
2122  SmallVector<Decl *, 8> DeclsInGroup;
2123  Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2124  D, ParsedTemplateInfo(), FRI);
2125  if (LateParsedAttrs.size() > 0)
2126  ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2127  D.complete(FirstDecl);
2128  if (FirstDecl)
2129  DeclsInGroup.push_back(FirstDecl);
2130 
2131  bool ExpectSemi = Context != DeclaratorContext::ForContext;
2132 
2133  // If we don't have a comma, it is either the end of the list (a ';') or an
2134  // error, bail out.
2135  SourceLocation CommaLoc;
2136  while (TryConsumeToken(tok::comma, CommaLoc)) {
2137  if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2138  // This comma was followed by a line-break and something which can't be
2139  // the start of a declarator. The comma was probably a typo for a
2140  // semicolon.
2141  Diag(CommaLoc, diag::err_expected_semi_declaration)
2142  << FixItHint::CreateReplacement(CommaLoc, ";");
2143  ExpectSemi = false;
2144  break;
2145  }
2146 
2147  // Parse the next declarator.
2148  D.clear();
2149  D.setCommaLoc(CommaLoc);
2150 
2151  // Accept attributes in an init-declarator. In the first declarator in a
2152  // declaration, these would be part of the declspec. In subsequent
2153  // declarators, they become part of the declarator itself, so that they
2154  // don't apply to declarators after *this* one. Examples:
2155  // short __attribute__((common)) var; -> declspec
2156  // short var __attribute__((common)); -> declarator
2157  // short x, __attribute__((common)) var; -> declarator
2158  MaybeParseGNUAttributes(D);
2159 
2160  // MSVC parses but ignores qualifiers after the comma as an extension.
2161  if (getLangOpts().MicrosoftExt)
2162  DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2163 
2164  ParseDeclarator(D);
2165  if (!D.isInvalidType()) {
2166  Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2167  D.complete(ThisDecl);
2168  if (ThisDecl)
2169  DeclsInGroup.push_back(ThisDecl);
2170  }
2171  }
2172 
2173  if (DeclEnd)
2174  *DeclEnd = Tok.getLocation();
2175 
2176  if (ExpectSemi &&
2177  ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
2178  ? diag::err_invalid_token_after_toplevel_declarator
2179  : diag::err_expected_semi_declaration)) {
2180  // Okay, there was no semicolon and one was expected. If we see a
2181  // declaration specifier, just assume it was missing and continue parsing.
2182  // Otherwise things are very confused and we skip to recover.
2183  if (!isDeclarationSpecifier()) {
2184  SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2185  TryConsumeToken(tok::semi);
2186  }
2187  }
2188 
2189  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2190 }
2191 
2192 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2193 /// declarator. Returns true on an error.
2194 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2195  // If a simple-asm-expr is present, parse it.
2196  if (Tok.is(tok::kw_asm)) {
2197  SourceLocation Loc;
2198  ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2199  if (AsmLabel.isInvalid()) {
2200  SkipUntil(tok::semi, StopBeforeMatch);
2201  return true;
2202  }
2203 
2204  D.setAsmLabel(AsmLabel.get());
2205  D.SetRangeEnd(Loc);
2206  }
2207 
2208  MaybeParseGNUAttributes(D);
2209  return false;
2210 }
2211 
2212 /// Parse 'declaration' after parsing 'declaration-specifiers
2213 /// declarator'. This method parses the remainder of the declaration
2214 /// (including any attributes or initializer, among other things) and
2215 /// finalizes the declaration.
2216 ///
2217 /// init-declarator: [C99 6.7]
2218 /// declarator
2219 /// declarator '=' initializer
2220 /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
2221 /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2222 /// [C++] declarator initializer[opt]
2223 ///
2224 /// [C++] initializer:
2225 /// [C++] '=' initializer-clause
2226 /// [C++] '(' expression-list ')'
2227 /// [C++0x] '=' 'default' [TODO]
2228 /// [C++0x] '=' 'delete'
2229 /// [C++0x] braced-init-list
2230 ///
2231 /// According to the standard grammar, =default and =delete are function
2232 /// definitions, but that definitely doesn't fit with the parser here.
2233 ///
2234 Decl *Parser::ParseDeclarationAfterDeclarator(
2235  Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2236  if (ParseAsmAttributesAfterDeclarator(D))
2237  return nullptr;
2238 
2239  return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2240 }
2241 
2242 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2243  Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2244  // RAII type used to track whether we're inside an initializer.
2245  struct InitializerScopeRAII {
2246  Parser &P;
2247  Declarator &D;
2248  Decl *ThisDecl;
2249 
2250  InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2251  : P(P), D(D), ThisDecl(ThisDecl) {
2252  if (ThisDecl && P.getLangOpts().CPlusPlus) {
2253  Scope *S = nullptr;
2254  if (D.getCXXScopeSpec().isSet()) {
2255  P.EnterScope(0);
2256  S = P.getCurScope();
2257  }
2258  P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2259  }
2260  }
2261  ~InitializerScopeRAII() { pop(); }
2262  void pop() {
2263  if (ThisDecl && P.getLangOpts().CPlusPlus) {
2264  Scope *S = nullptr;
2265  if (D.getCXXScopeSpec().isSet())
2266  S = P.getCurScope();
2267  P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2268  if (S)
2269  P.ExitScope();
2270  }
2271  ThisDecl = nullptr;
2272  }
2273  };
2274 
2275  // Inform the current actions module that we just parsed this declarator.
2276  Decl *ThisDecl = nullptr;
2277  switch (TemplateInfo.Kind) {
2278  case ParsedTemplateInfo::NonTemplate:
2279  ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2280  break;
2281 
2282  case ParsedTemplateInfo::Template:
2283  case ParsedTemplateInfo::ExplicitSpecialization: {
2284  ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2285  *TemplateInfo.TemplateParams,
2286  D);
2287  if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2288  // Re-direct this decl to refer to the templated decl so that we can
2289  // initialize it.
2290  ThisDecl = VT->getTemplatedDecl();
2291  break;
2292  }
2293  case ParsedTemplateInfo::ExplicitInstantiation: {
2294  if (Tok.is(tok::semi)) {
2295  DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2296  getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2297  if (ThisRes.isInvalid()) {
2298  SkipUntil(tok::semi, StopBeforeMatch);
2299  return nullptr;
2300  }
2301  ThisDecl = ThisRes.get();
2302  } else {
2303  // FIXME: This check should be for a variable template instantiation only.
2304 
2305  // Check that this is a valid instantiation
2307  // If the declarator-id is not a template-id, issue a diagnostic and
2308  // recover by ignoring the 'template' keyword.
2309  Diag(Tok, diag::err_template_defn_explicit_instantiation)
2310  << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2311  ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2312  } else {
2313  SourceLocation LAngleLoc =
2314  PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2315  Diag(D.getIdentifierLoc(),
2316  diag::err_explicit_instantiation_with_definition)
2317  << SourceRange(TemplateInfo.TemplateLoc)
2318  << FixItHint::CreateInsertion(LAngleLoc, "<>");
2319 
2320  // Recover as if it were an explicit specialization.
2321  TemplateParameterLists FakedParamLists;
2322  FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2323  0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2324  LAngleLoc, nullptr));
2325 
2326  ThisDecl =
2327  Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2328  }
2329  }
2330  break;
2331  }
2332  }
2333 
2334  // Parse declarator '=' initializer.
2335  // If a '==' or '+=' is found, suggest a fixit to '='.
2336  if (isTokenEqualOrEqualTypo()) {
2337  SourceLocation EqualLoc = ConsumeToken();
2338 
2339  if (Tok.is(tok::kw_delete)) {
2340  if (D.isFunctionDeclarator())
2341  Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2342  << 1 /* delete */;
2343  else
2344  Diag(ConsumeToken(), diag::err_deleted_non_function);
2345  } else if (Tok.is(tok::kw_default)) {
2346  if (D.isFunctionDeclarator())
2347  Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2348  << 0 /* default */;
2349  else
2350  Diag(ConsumeToken(), diag::err_default_special_members);
2351  } else {
2352  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2353 
2354  if (Tok.is(tok::code_completion)) {
2355  Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2356  Actions.FinalizeDeclaration(ThisDecl);
2357  cutOffParsing();
2358  return nullptr;
2359  }
2360 
2361  PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2362  ExprResult Init = ParseInitializer();
2363 
2364  // If this is the only decl in (possibly) range based for statement,
2365  // our best guess is that the user meant ':' instead of '='.
2366  if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2367  Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2368  << FixItHint::CreateReplacement(EqualLoc, ":");
2369  // We are trying to stop parser from looking for ';' in this for
2370  // statement, therefore preventing spurious errors to be issued.
2371  FRI->ColonLoc = EqualLoc;
2372  Init = ExprError();
2373  FRI->RangeExpr = Init;
2374  }
2375 
2376  InitScope.pop();
2377 
2378  if (Init.isInvalid()) {
2379  SmallVector<tok::TokenKind, 2> StopTokens;
2380  StopTokens.push_back(tok::comma);
2383  StopTokens.push_back(tok::r_paren);
2384  SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2385  Actions.ActOnInitializerError(ThisDecl);
2386  } else
2387  Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2388  /*DirectInit=*/false);
2389  }
2390  } else if (Tok.is(tok::l_paren)) {
2391  // Parse C++ direct initializer: '(' expression-list ')'
2392  BalancedDelimiterTracker T(*this, tok::l_paren);
2393  T.consumeOpen();
2394 
2395  ExprVector Exprs;
2396  CommaLocsTy CommaLocs;
2397 
2398  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2399 
2400  auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2401  auto RunSignatureHelp = [&]() {
2402  QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2403  getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2404  ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2405  CalledSignatureHelp = true;
2406  return PreferredType;
2407  };
2408  auto SetPreferredType = [&] {
2409  PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2410  };
2411 
2412  llvm::function_ref<void()> ExpressionStarts;
2413  if (ThisVarDecl) {
2414  // ParseExpressionList can sometimes succeed even when ThisDecl is not
2415  // VarDecl. This is an error and it is reported in a call to
2416  // Actions.ActOnInitializerError(). However, we call
2417  // ProduceConstructorSignatureHelp only on VarDecls.
2418  ExpressionStarts = SetPreferredType;
2419  }
2420  if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2421  if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2422  Actions.ProduceConstructorSignatureHelp(
2423  getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2424  ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2425  CalledSignatureHelp = true;
2426  }
2427  Actions.ActOnInitializerError(ThisDecl);
2428  SkipUntil(tok::r_paren, StopAtSemi);
2429  } else {
2430  // Match the ')'.
2431  T.consumeClose();
2432 
2433  assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2434  "Unexpected number of commas!");
2435 
2436  InitScope.pop();
2437 
2438  ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2439  T.getCloseLocation(),
2440  Exprs);
2441  Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2442  /*DirectInit=*/true);
2443  }
2444  } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2445  (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2446  // Parse C++0x braced-init-list.
2447  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2448 
2449  InitializerScopeRAII InitScope(*this, D, ThisDecl);
2450 
2451  ExprResult Init(ParseBraceInitializer());
2452 
2453  InitScope.pop();
2454 
2455  if (Init.isInvalid()) {
2456  Actions.ActOnInitializerError(ThisDecl);
2457  } else
2458  Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2459 
2460  } else {
2461  Actions.ActOnUninitializedDecl(ThisDecl);
2462  }
2463 
2464  Actions.FinalizeDeclaration(ThisDecl);
2465 
2466  return ThisDecl;
2467 }
2468 
2469 /// ParseSpecifierQualifierList
2470 /// specifier-qualifier-list:
2471 /// type-specifier specifier-qualifier-list[opt]
2472 /// type-qualifier specifier-qualifier-list[opt]
2473 /// [GNU] attributes specifier-qualifier-list[opt]
2474 ///
2475 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2476  DeclSpecContext DSC) {
2477  /// specifier-qualifier-list is a subset of declaration-specifiers. Just
2478  /// parse declaration-specifiers and complain about extra stuff.
2479  /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2480  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2481 
2482  // Validate declspec for type-name.
2483  unsigned Specs = DS.getParsedSpecifiers();
2484  if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2485  Diag(Tok, diag::err_expected_type);
2486  DS.SetTypeSpecError();
2487  } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2488  Diag(Tok, diag::err_typename_requires_specqual);
2489  if (!DS.hasTypeSpecifier())
2490  DS.SetTypeSpecError();
2491  }
2492 
2493  // Issue diagnostic and remove storage class if present.
2494  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2495  if (DS.getStorageClassSpecLoc().isValid())
2496  Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2497  else
2499  diag::err_typename_invalid_storageclass);
2501  }
2502 
2503  // Issue diagnostic and remove function specifier if present.
2504  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2505  if (DS.isInlineSpecified())
2506  Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2507  if (DS.isVirtualSpecified())
2508  Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2509  if (DS.hasExplicitSpecifier())
2510  Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2511  DS.ClearFunctionSpecs();
2512  }
2513 
2514  // Issue diagnostic and remove constexpr specifier if present.
2515  if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2516  Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2517  << DS.getConstexprSpecifier();
2518  DS.ClearConstexprSpec();
2519  }
2520 }
2521 
2522 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2523 /// specified token is valid after the identifier in a declarator which
2524 /// immediately follows the declspec. For example, these things are valid:
2525 ///
2526 /// int x [ 4]; // direct-declarator
2527 /// int x ( int y); // direct-declarator
2528 /// int(int x ) // direct-declarator
2529 /// int x ; // simple-declaration
2530 /// int x = 17; // init-declarator-list
2531 /// int x , y; // init-declarator-list
2532 /// int x __asm__ ("foo"); // init-declarator-list
2533 /// int x : 4; // struct-declarator
2534 /// int x { 5}; // C++'0x unified initializers
2535 ///
2536 /// This is not, because 'x' does not immediately follow the declspec (though
2537 /// ')' happens to be valid anyway).
2538 /// int (x)
2539 ///
2541  return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2542  tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2543  tok::colon);
2544 }
2545 
2546 /// ParseImplicitInt - This method is called when we have an non-typename
2547 /// identifier in a declspec (which normally terminates the decl spec) when
2548 /// the declspec has no type specifier. In this case, the declspec is either
2549 /// malformed or is "implicit int" (in K&R and C89).
2550 ///
2551 /// This method handles diagnosing this prettily and returns false if the
2552 /// declspec is done being processed. If it recovers and thinks there may be
2553 /// other pieces of declspec after it, it returns true.
2554 ///
2555 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2556  const ParsedTemplateInfo &TemplateInfo,
2557  AccessSpecifier AS, DeclSpecContext DSC,
2558  ParsedAttributesWithRange &Attrs) {
2559  assert(Tok.is(tok::identifier) && "should have identifier");
2560 
2561  SourceLocation Loc = Tok.getLocation();
2562  // If we see an identifier that is not a type name, we normally would
2563  // parse it as the identifier being declared. However, when a typename
2564  // is typo'd or the definition is not included, this will incorrectly
2565  // parse the typename as the identifier name and fall over misparsing
2566  // later parts of the diagnostic.
2567  //
2568  // As such, we try to do some look-ahead in cases where this would
2569  // otherwise be an "implicit-int" case to see if this is invalid. For
2570  // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
2571  // an identifier with implicit int, we'd get a parse error because the
2572  // next token is obviously invalid for a type. Parse these as a case
2573  // with an invalid type specifier.
2574  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2575 
2576  // Since we know that this either implicit int (which is rare) or an
2577  // error, do lookahead to try to do better recovery. This never applies
2578  // within a type specifier. Outside of C++, we allow this even if the
2579  // language doesn't "officially" support implicit int -- we support
2580  // implicit int as an extension in C99 and C11.
2581  if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2583  // If this token is valid for implicit int, e.g. "static x = 4", then
2584  // we just avoid eating the identifier, so it will be parsed as the
2585  // identifier in the declarator.
2586  return false;
2587  }
2588 
2589  // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2590  // for incomplete declarations such as `pipe p`.
2591  if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2592  return false;
2593 
2594  if (getLangOpts().CPlusPlus &&
2596  // Don't require a type specifier if we have the 'auto' storage class
2597  // specifier in C++98 -- we'll promote it to a type specifier.
2598  if (SS)
2599  AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2600  return false;
2601  }
2602 
2603  if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2604  getLangOpts().MSVCCompat) {
2605  // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2606  // Give Sema a chance to recover if we are in a template with dependent base
2607  // classes.
2608  if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2609  *Tok.getIdentifierInfo(), Tok.getLocation(),
2610  DSC == DeclSpecContext::DSC_template_type_arg)) {
2611  const char *PrevSpec;
2612  unsigned DiagID;
2613  DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2614  Actions.getASTContext().getPrintingPolicy());
2615  DS.SetRangeEnd(Tok.getLocation());
2616  ConsumeToken();
2617  return false;
2618  }
2619  }
2620 
2621  // Otherwise, if we don't consume this token, we are going to emit an
2622  // error anyway. Try to recover from various common problems. Check
2623  // to see if this was a reference to a tag name without a tag specified.
2624  // This is a common problem in C (saying 'foo' instead of 'struct foo').
2625  //
2626  // C++ doesn't need this, and isTagName doesn't take SS.
2627  if (SS == nullptr) {
2628  const char *TagName = nullptr, *FixitTagName = nullptr;
2629  tok::TokenKind TagKind = tok::unknown;
2630 
2631  switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2632  default: break;
2633  case DeclSpec::TST_enum:
2634  TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
2635  case DeclSpec::TST_union:
2636  TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2637  case DeclSpec::TST_struct:
2638  TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2640  TagName="__interface"; FixitTagName = "__interface ";
2641  TagKind=tok::kw___interface;break;
2642  case DeclSpec::TST_class:
2643  TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2644  }
2645 
2646  if (TagName) {
2647  IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2648  LookupResult R(Actions, TokenName, SourceLocation(),
2650 
2651  Diag(Loc, diag::err_use_of_tag_name_without_tag)
2652  << TokenName << TagName << getLangOpts().CPlusPlus
2653  << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2654 
2655  if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2656  for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2657  I != IEnd; ++I)
2658  Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2659  << TokenName << TagName;
2660  }
2661 
2662  // Parse this as a tag as if the missing tag were present.
2663  if (TagKind == tok::kw_enum)
2664  ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2665  DeclSpecContext::DSC_normal);
2666  else
2667  ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2668  /*EnteringContext*/ false,
2669  DeclSpecContext::DSC_normal, Attrs);
2670  return true;
2671  }
2672  }
2673 
2674  // Determine whether this identifier could plausibly be the name of something
2675  // being declared (with a missing type).
2676  if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2677  DSC == DeclSpecContext::DSC_class)) {
2678  // Look ahead to the next token to try to figure out what this declaration
2679  // was supposed to be.
2680  switch (NextToken().getKind()) {
2681  case tok::l_paren: {
2682  // static x(4); // 'x' is not a type
2683  // x(int n); // 'x' is not a type
2684  // x (*p)[]; // 'x' is a type
2685  //
2686  // Since we're in an error case, we can afford to perform a tentative
2687  // parse to determine which case we're in.
2688  TentativeParsingAction PA(*this);
2689  ConsumeToken();
2690  TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2691  PA.Revert();
2692 
2693  if (TPR != TPResult::False) {
2694  // The identifier is followed by a parenthesized declarator.
2695  // It's supposed to be a type.
2696  break;
2697  }
2698 
2699  // If we're in a context where we could be declaring a constructor,
2700  // check whether this is a constructor declaration with a bogus name.
2701  if (DSC == DeclSpecContext::DSC_class ||
2702  (DSC == DeclSpecContext::DSC_top_level && SS)) {
2703  IdentifierInfo *II = Tok.getIdentifierInfo();
2704  if (Actions.isCurrentClassNameTypo(II, SS)) {
2705  Diag(Loc, diag::err_constructor_bad_name)
2706  << Tok.getIdentifierInfo() << II
2707  << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2708  Tok.setIdentifierInfo(II);
2709  }
2710  }
2711  // Fall through.
2712  LLVM_FALLTHROUGH;
2713  }
2714  case tok::comma:
2715  case tok::equal:
2716  case tok::kw_asm:
2717  case tok::l_brace:
2718  case tok::l_square:
2719  case tok::semi:
2720  // This looks like a variable or function declaration. The type is
2721  // probably missing. We're done parsing decl-specifiers.
2722  // But only if we are not in a function prototype scope.
2723  if (getCurScope()->isFunctionPrototypeScope())
2724  break;
2725  if (SS)
2726  AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2727  return false;
2728 
2729  default:
2730  // This is probably supposed to be a type. This includes cases like:
2731  // int f(itn);
2732  // struct S { unsinged : 4; };
2733  break;
2734  }
2735  }
2736 
2737  // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2738  // and attempt to recover.
2739  ParsedType T;
2740  IdentifierInfo *II = Tok.getIdentifierInfo();
2741  bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2742  Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2743  IsTemplateName);
2744  if (T) {
2745  // The action has suggested that the type T could be used. Set that as
2746  // the type in the declaration specifiers, consume the would-be type
2747  // name token, and we're done.
2748  const char *PrevSpec;
2749  unsigned DiagID;
2750  DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2751  Actions.getASTContext().getPrintingPolicy());
2752  DS.SetRangeEnd(Tok.getLocation());
2753  ConsumeToken();
2754  // There may be other declaration specifiers after this.
2755  return true;
2756  } else if (II != Tok.getIdentifierInfo()) {
2757  // If no type was suggested, the correction is to a keyword
2758  Tok.setKind(II->getTokenID());
2759  // There may be other declaration specifiers after this.
2760  return true;
2761  }
2762 
2763  // Otherwise, the action had no suggestion for us. Mark this as an error.
2764  DS.SetTypeSpecError();
2765  DS.SetRangeEnd(Tok.getLocation());
2766  ConsumeToken();
2767 
2768  // Eat any following template arguments.
2769  if (IsTemplateName) {
2770  SourceLocation LAngle, RAngle;
2771  TemplateArgList Args;
2772  ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2773  }
2774 
2775  // TODO: Could inject an invalid typedef decl in an enclosing scope to
2776  // avoid rippling error messages on subsequent uses of the same type,
2777  // could be useful if #include was forgotten.
2778  return true;
2779 }
2780 
2781 /// Determine the declaration specifier context from the declarator
2782 /// context.
2783 ///
2784 /// \param Context the declarator context, which is one of the
2785 /// DeclaratorContext enumerator values.
2786 Parser::DeclSpecContext
2787 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2788  if (Context == DeclaratorContext::MemberContext)
2789  return DeclSpecContext::DSC_class;
2790  if (Context == DeclaratorContext::FileContext)
2791  return DeclSpecContext::DSC_top_level;
2793  return DeclSpecContext::DSC_template_param;
2794  if (Context == DeclaratorContext::TemplateArgContext ||
2796  return DeclSpecContext::DSC_template_type_arg;
2799  return DeclSpecContext::DSC_trailing;
2800  if (Context == DeclaratorContext::AliasDeclContext ||
2802  return DeclSpecContext::DSC_alias_declaration;
2803  return DeclSpecContext::DSC_normal;
2804 }
2805 
2806 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2807 ///
2808 /// FIXME: Simply returns an alignof() expression if the argument is a
2809 /// type. Ideally, the type should be propagated directly into Sema.
2810 ///
2811 /// [C11] type-id
2812 /// [C11] constant-expression
2813 /// [C++0x] type-id ...[opt]
2814 /// [C++0x] assignment-expression ...[opt]
2815 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2816  SourceLocation &EllipsisLoc) {
2817  ExprResult ER;
2818  if (isTypeIdInParens()) {
2819  SourceLocation TypeLoc = Tok.getLocation();
2820  ParsedType Ty = ParseTypeName().get();
2821  SourceRange TypeRange(Start, Tok.getLocation());
2822  ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2823  Ty.getAsOpaquePtr(), TypeRange);
2824  } else
2825  ER = ParseConstantExpression();
2826 
2827  if (getLangOpts().CPlusPlus11)
2828  TryConsumeToken(tok::ellipsis, EllipsisLoc);
2829 
2830  return ER;
2831 }
2832 
2833 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2834 /// attribute to Attrs.
2835 ///
2836 /// alignment-specifier:
2837 /// [C11] '_Alignas' '(' type-id ')'
2838 /// [C11] '_Alignas' '(' constant-expression ')'
2839 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2840 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2841 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2842  SourceLocation *EndLoc) {
2843  assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2844  "Not an alignment-specifier!");
2845 
2846  IdentifierInfo *KWName = Tok.getIdentifierInfo();
2847  SourceLocation KWLoc = ConsumeToken();
2848 
2849  BalancedDelimiterTracker T(*this, tok::l_paren);
2850  if (T.expectAndConsume())
2851  return;
2852 
2853  SourceLocation EllipsisLoc;
2854  ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2855  if (ArgExpr.isInvalid()) {
2856  T.skipToEnd();
2857  return;
2858  }
2859 
2860  T.consumeClose();
2861  if (EndLoc)
2862  *EndLoc = T.getCloseLocation();
2863 
2864  ArgsVector ArgExprs;
2865  ArgExprs.push_back(ArgExpr.get());
2866  Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2867  ParsedAttr::AS_Keyword, EllipsisLoc);
2868 }
2869 
2870 /// Determine whether we're looking at something that might be a declarator
2871 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2872 /// diagnose a missing semicolon after a prior tag definition in the decl
2873 /// specifier.
2874 ///
2875 /// \return \c true if an error occurred and this can't be any kind of
2876 /// declaration.
2877 bool
2878 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2879  DeclSpecContext DSContext,
2880  LateParsedAttrList *LateAttrs) {
2881  assert(DS.hasTagDefinition() && "shouldn't call this");
2882 
2883  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2884  DSContext == DeclSpecContext::DSC_top_level);
2885 
2886  if (getLangOpts().CPlusPlus &&
2887  Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2888  tok::annot_template_id) &&
2889  TryAnnotateCXXScopeToken(EnteringContext)) {
2891  return true;
2892  }
2893 
2894  bool HasScope = Tok.is(tok::annot_cxxscope);
2895  // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2896  Token AfterScope = HasScope ? NextToken() : Tok;
2897 
2898  // Determine whether the following tokens could possibly be a
2899  // declarator.
2900  bool MightBeDeclarator = true;
2901  if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2902  // A declarator-id can't start with 'typename'.
2903  MightBeDeclarator = false;
2904  } else if (AfterScope.is(tok::annot_template_id)) {
2905  // If we have a type expressed as a template-id, this cannot be a
2906  // declarator-id (such a type cannot be redeclared in a simple-declaration).
2907  TemplateIdAnnotation *Annot =
2908  static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2909  if (Annot->Kind == TNK_Type_template)
2910  MightBeDeclarator = false;
2911  } else if (AfterScope.is(tok::identifier)) {
2912  const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2913 
2914  // These tokens cannot come after the declarator-id in a
2915  // simple-declaration, and are likely to come after a type-specifier.
2916  if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2917  tok::annot_cxxscope, tok::coloncolon)) {
2918  // Missing a semicolon.
2919  MightBeDeclarator = false;
2920  } else if (HasScope) {
2921  // If the declarator-id has a scope specifier, it must redeclare a
2922  // previously-declared entity. If that's a type (and this is not a
2923  // typedef), that's an error.
2924  CXXScopeSpec SS;
2925  Actions.RestoreNestedNameSpecifierAnnotation(
2926  Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2927  IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2928  Sema::NameClassification Classification = Actions.ClassifyName(
2929  getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2930  /*IsAddressOfOperand=*/false, /*CCC=*/nullptr);
2931  switch (Classification.getKind()) {
2932  case Sema::NC_Error:
2934  return true;
2935 
2936  case Sema::NC_Keyword:
2938  llvm_unreachable("typo correction and nested name specifiers not "
2939  "possible here");
2940 
2941  case Sema::NC_Type:
2942  case Sema::NC_TypeTemplate:
2943  // Not a previously-declared non-type entity.
2944  MightBeDeclarator = false;
2945  break;
2946 
2947  case Sema::NC_Unknown:
2948  case Sema::NC_Expression:
2949  case Sema::NC_VarTemplate:
2952  // Might be a redeclaration of a prior entity.
2953  break;
2954  }
2955  }
2956  }
2957 
2958  if (MightBeDeclarator)
2959  return false;
2960 
2961  const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2962  Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
2963  diag::err_expected_after)
2964  << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2965 
2966  // Try to recover from the typo, by dropping the tag definition and parsing
2967  // the problematic tokens as a type.
2968  //
2969  // FIXME: Split the DeclSpec into pieces for the standalone
2970  // declaration and pieces for the following declaration, instead
2971  // of assuming that all the other pieces attach to new declaration,
2972  // and call ParsedFreeStandingDeclSpec as appropriate.
2973  DS.ClearTypeSpecType();
2974  ParsedTemplateInfo NotATemplate;
2975  ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2976  return false;
2977 }
2978 
2979 // Choose the apprpriate diagnostic error for why fixed point types are
2980 // disabled, set the previous specifier, and mark as invalid.
2981 static void SetupFixedPointError(const LangOptions &LangOpts,
2982  const char *&PrevSpec, unsigned &DiagID,
2983  bool &isInvalid) {
2984  assert(!LangOpts.FixedPoint);
2985  DiagID = diag::err_fixed_point_not_enabled;
2986  PrevSpec = ""; // Not used by diagnostic
2987  isInvalid = true;
2988 }
2989 
2990 /// ParseDeclarationSpecifiers
2991 /// declaration-specifiers: [C99 6.7]
2992 /// storage-class-specifier declaration-specifiers[opt]
2993 /// type-specifier declaration-specifiers[opt]
2994 /// [C99] function-specifier declaration-specifiers[opt]
2995 /// [C11] alignment-specifier declaration-specifiers[opt]
2996 /// [GNU] attributes declaration-specifiers[opt]
2997 /// [Clang] '__module_private__' declaration-specifiers[opt]
2998 /// [ObjC1] '__kindof' declaration-specifiers[opt]
2999 ///
3000 /// storage-class-specifier: [C99 6.7.1]
3001 /// 'typedef'
3002 /// 'extern'
3003 /// 'static'
3004 /// 'auto'
3005 /// 'register'
3006 /// [C++] 'mutable'
3007 /// [C++11] 'thread_local'
3008 /// [C11] '_Thread_local'
3009 /// [GNU] '__thread'
3010 /// function-specifier: [C99 6.7.4]
3011 /// [C99] 'inline'
3012 /// [C++] 'virtual'
3013 /// [C++] 'explicit'
3014 /// [OpenCL] '__kernel'
3015 /// 'friend': [C++ dcl.friend]
3016 /// 'constexpr': [C++0x dcl.constexpr]
3017 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
3018  const ParsedTemplateInfo &TemplateInfo,
3019  AccessSpecifier AS,
3020  DeclSpecContext DSContext,
3021  LateParsedAttrList *LateAttrs) {
3022  if (DS.getSourceRange().isInvalid()) {
3023  // Start the range at the current token but make the end of the range
3024  // invalid. This will make the entire range invalid unless we successfully
3025  // consume a token.
3026  DS.SetRangeStart(Tok.getLocation());
3028  }
3029 
3030  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3031  DSContext == DeclSpecContext::DSC_top_level);
3032  bool AttrsLastTime = false;
3033  ParsedAttributesWithRange attrs(AttrFactory);
3034  // We use Sema's policy to get bool macros right.
3035  PrintingPolicy Policy = Actions.getPrintingPolicy();
3036  while (1) {
3037  bool isInvalid = false;
3038  bool isStorageClass = false;
3039  const char *PrevSpec = nullptr;
3040  unsigned DiagID = 0;
3041 
3042  // This value needs to be set to the location of the last token if the last
3043  // token of the specifier is already consumed.
3044  SourceLocation ConsumedEnd;
3045 
3046  // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3047  // implementation for VS2013 uses _Atomic as an identifier for one of the
3048  // classes in <atomic>.
3049  //
3050  // A typedef declaration containing _Atomic<...> is among the places where
3051  // the class is used. If we are currently parsing such a declaration, treat
3052  // the token as an identifier.
3053  if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3055  !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3056  Tok.setKind(tok::identifier);
3057 
3058  SourceLocation Loc = Tok.getLocation();
3059 
3060  switch (Tok.getKind()) {
3061  default:
3062  DoneWithDeclSpec:
3063  if (!AttrsLastTime)
3064  ProhibitAttributes(attrs);
3065  else {
3066  // Reject C++11 attributes that appertain to decl specifiers as
3067  // we don't support any C++11 attributes that appertain to decl
3068  // specifiers. This also conforms to what g++ 4.8 is doing.
3069  ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
3070 
3071  DS.takeAttributesFrom(attrs);
3072  }
3073 
3074  // If this is not a declaration specifier token, we're done reading decl
3075  // specifiers. First verify that DeclSpec's are consistent.
3076  DS.Finish(Actions, Policy);
3077  return;
3078 
3079  case tok::l_square:
3080  case tok::kw_alignas:
3081  if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3082  goto DoneWithDeclSpec;
3083 
3084  ProhibitAttributes(attrs);
3085  // FIXME: It would be good to recover by accepting the attributes,
3086  // but attempting to do that now would cause serious
3087  // madness in terms of diagnostics.
3088  attrs.clear();
3089  attrs.Range = SourceRange();
3090 
3091  ParseCXX11Attributes(attrs);
3092  AttrsLastTime = true;
3093  continue;
3094 
3095  case tok::code_completion: {
3097  if (DS.hasTypeSpecifier()) {
3098  bool AllowNonIdentifiers
3103  Scope::AtCatchScope)) == 0;
3104  bool AllowNestedNameSpecifiers
3105  = DSContext == DeclSpecContext::DSC_top_level ||
3106  (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3107 
3108  Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3109  AllowNonIdentifiers,
3110  AllowNestedNameSpecifiers);
3111  return cutOffParsing();
3112  }
3113 
3114  if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3116  else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3117  CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3119  else if (DSContext == DeclSpecContext::DSC_class)
3120  CCC = Sema::PCC_Class;
3121  else if (CurParsedObjCImpl)
3123 
3124  Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3125  return cutOffParsing();
3126  }
3127 
3128  case tok::coloncolon: // ::foo::bar
3129  // C++ scope specifier. Annotate and loop, or bail out on error.
3130  if (TryAnnotateCXXScopeToken(EnteringContext)) {
3131  if (!DS.hasTypeSpecifier())
3132  DS.SetTypeSpecError();
3133  goto DoneWithDeclSpec;
3134  }
3135  if (Tok.is(tok::coloncolon)) // ::new or ::delete
3136  goto DoneWithDeclSpec;
3137  continue;
3138 
3139  case tok::annot_cxxscope: {
3140  if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3141  goto DoneWithDeclSpec;
3142 
3143  CXXScopeSpec SS;
3144  Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3145  Tok.getAnnotationRange(),
3146  SS);
3147 
3148  // We are looking for a qualified typename.
3149  Token Next = NextToken();
3150  if (Next.is(tok::annot_template_id) &&
3151  static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3152  ->Kind == TNK_Type_template) {
3153  // We have a qualified template-id, e.g., N::A<int>
3154 
3155  // If this would be a valid constructor declaration with template
3156  // arguments, we will reject the attempt to form an invalid type-id
3157  // referring to the injected-class-name when we annotate the token,
3158  // per C++ [class.qual]p2.
3159  //
3160  // To improve diagnostics for this case, parse the declaration as a
3161  // constructor (and reject the extra template arguments later).
3162  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
3163  if ((DSContext == DeclSpecContext::DSC_top_level ||
3164  DSContext == DeclSpecContext::DSC_class) &&
3165  TemplateId->Name &&
3166  Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3167  isConstructorDeclarator(/*Unqualified*/ false)) {
3168  // The user meant this to be an out-of-line constructor
3169  // definition, but template arguments are not allowed
3170  // there. Just allow this as a constructor; we'll
3171  // complain about it later.
3172  goto DoneWithDeclSpec;
3173  }
3174 
3175  DS.getTypeSpecScope() = SS;
3176  ConsumeAnnotationToken(); // The C++ scope.
3177  assert(Tok.is(tok::annot_template_id) &&
3178  "ParseOptionalCXXScopeSpecifier not working");
3179  AnnotateTemplateIdTokenAsType();
3180  continue;
3181  }
3182 
3183  if (Next.is(tok::annot_typename)) {
3184  DS.getTypeSpecScope() = SS;
3185  ConsumeAnnotationToken(); // The C++ scope.
3186  if (Tok.getAnnotationValue()) {
3187  ParsedType T = getTypeAnnotation(Tok);
3188  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3189  Tok.getAnnotationEndLoc(),
3190  PrevSpec, DiagID, T, Policy);
3191  if (isInvalid)
3192  break;
3193  }
3194  else
3195  DS.SetTypeSpecError();
3196  DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3197  ConsumeAnnotationToken(); // The typename
3198  }
3199 
3200  if (Next.isNot(tok::identifier))
3201  goto DoneWithDeclSpec;
3202 
3203  // Check whether this is a constructor declaration. If we're in a
3204  // context where the identifier could be a class name, and it has the
3205  // shape of a constructor declaration, process it as one.
3206  if ((DSContext == DeclSpecContext::DSC_top_level ||
3207  DSContext == DeclSpecContext::DSC_class) &&
3208  Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3209  &SS) &&
3210  isConstructorDeclarator(/*Unqualified*/ false))
3211  goto DoneWithDeclSpec;
3212 
3213  ParsedType TypeRep =
3214  Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3215  getCurScope(), &SS, false, false, nullptr,
3216  /*IsCtorOrDtorName=*/false,
3217  /*WantNontrivialTypeSourceInfo=*/true,
3218  isClassTemplateDeductionContext(DSContext));
3219 
3220  // If the referenced identifier is not a type, then this declspec is
3221  // erroneous: We already checked about that it has no type specifier, and
3222  // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
3223  // typename.
3224  if (!TypeRep) {
3225  // Eat the scope spec so the identifier is current.
3226  ConsumeAnnotationToken();
3227  ParsedAttributesWithRange Attrs(AttrFactory);
3228  if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3229  if (!Attrs.empty()) {
3230  AttrsLastTime = true;
3231  attrs.takeAllFrom(Attrs);
3232  }
3233  continue;
3234  }
3235  goto DoneWithDeclSpec;
3236  }
3237 
3238  DS.getTypeSpecScope() = SS;
3239  ConsumeAnnotationToken(); // The C++ scope.
3240 
3241  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3242  DiagID, TypeRep, Policy);
3243  if (isInvalid)
3244  break;
3245 
3246  DS.SetRangeEnd(Tok.getLocation());
3247  ConsumeToken(); // The typename.
3248 
3249  continue;
3250  }
3251 
3252  case tok::annot_typename: {
3253  // If we've previously seen a tag definition, we were almost surely
3254  // missing a semicolon after it.
3255  if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3256  goto DoneWithDeclSpec;
3257 
3258  if (Tok.getAnnotationValue()) {
3259  ParsedType T = getTypeAnnotation(Tok);
3260  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3261  DiagID, T, Policy);
3262  } else
3263  DS.SetTypeSpecError();
3264 
3265  if (isInvalid)
3266  break;
3267 
3268  DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3269  ConsumeAnnotationToken(); // The typename
3270 
3271  continue;
3272  }
3273 
3274  case tok::kw___is_signed:
3275  // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3276  // typically treats it as a trait. If we see __is_signed as it appears
3277  // in libstdc++, e.g.,
3278  //
3279  // static const bool __is_signed;
3280  //
3281  // then treat __is_signed as an identifier rather than as a keyword.
3282  if (DS.getTypeSpecType() == TST_bool &&
3285  TryKeywordIdentFallback(true);
3286 
3287  // We're done with the declaration-specifiers.
3288  goto DoneWithDeclSpec;
3289 
3290  // typedef-name
3291  case tok::kw___super:
3292  case tok::kw_decltype:
3293  case tok::identifier: {
3294  // This identifier can only be a typedef name if we haven't already seen
3295  // a type-specifier. Without this check we misparse:
3296  // typedef int X; struct Y { short X; }; as 'short int'.
3297  if (DS.hasTypeSpecifier())
3298  goto DoneWithDeclSpec;
3299 
3300  // If the token is an identifier named "__declspec" and Microsoft
3301  // extensions are not enabled, it is likely that there will be cascading
3302  // parse errors if this really is a __declspec attribute. Attempt to
3303  // recognize that scenario and recover gracefully.
3304  if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3305  Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3306  Diag(Loc, diag::err_ms_attributes_not_enabled);
3307 
3308  // The next token should be an open paren. If it is, eat the entire
3309  // attribute declaration and continue.
3310  if (NextToken().is(tok::l_paren)) {
3311  // Consume the __declspec identifier.
3312  ConsumeToken();
3313 
3314  // Eat the parens and everything between them.
3315  BalancedDelimiterTracker T(*this, tok::l_paren);
3316  if (T.consumeOpen()) {
3317  assert(false && "Not a left paren?");
3318  return;
3319  }
3320  T.skipToEnd();
3321  continue;
3322  }
3323  }
3324 
3325  // In C++, check to see if this is a scope specifier like foo::bar::, if
3326  // so handle it as such. This is important for ctor parsing.
3327  if (getLangOpts().CPlusPlus) {
3328  if (TryAnnotateCXXScopeToken(EnteringContext)) {
3329  DS.SetTypeSpecError();
3330  goto DoneWithDeclSpec;
3331  }
3332  if (!Tok.is(tok::identifier))
3333  continue;
3334  }
3335 
3336  // Check for need to substitute AltiVec keyword tokens.
3337  if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3338  break;
3339 
3340  // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3341  // allow the use of a typedef name as a type specifier.
3342  if (DS.isTypeAltiVecVector())
3343  goto DoneWithDeclSpec;
3344 
3345  if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3346  isObjCInstancetype()) {
3347  ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3348  assert(TypeRep);
3349  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3350  DiagID, TypeRep, Policy);
3351  if (isInvalid)
3352  break;
3353 
3354  DS.SetRangeEnd(Loc);
3355  ConsumeToken();
3356  continue;
3357  }
3358 
3359  // If we're in a context where the identifier could be a class name,
3360  // check whether this is a constructor declaration.
3361  if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3362  Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3363  isConstructorDeclarator(/*Unqualified*/true))
3364  goto DoneWithDeclSpec;
3365 
3366  ParsedType TypeRep = Actions.getTypeName(
3367  *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3368  false, false, nullptr, false, false,
3369  isClassTemplateDeductionContext(DSContext));
3370 
3371  // If this is not a typedef name, don't parse it as part of the declspec,
3372  // it must be an implicit int or an error.
3373  if (!TypeRep) {
3374  ParsedAttributesWithRange Attrs(AttrFactory);
3375  if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3376  if (!Attrs.empty()) {
3377  AttrsLastTime = true;
3378  attrs.takeAllFrom(Attrs);
3379  }
3380  continue;
3381  }
3382  goto DoneWithDeclSpec;
3383  }
3384 
3385  // Likewise, if this is a context where the identifier could be a template
3386  // name, check whether this is a deduction guide declaration.
3387  if (getLangOpts().CPlusPlus17 &&
3388  (DSContext == DeclSpecContext::DSC_class ||
3389  DSContext == DeclSpecContext::DSC_top_level) &&
3390  Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3391  Tok.getLocation()) &&
3392  isConstructorDeclarator(/*Unqualified*/ true,
3393  /*DeductionGuide*/ true))
3394  goto DoneWithDeclSpec;
3395 
3396  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3397  DiagID, TypeRep, Policy);
3398  if (isInvalid)
3399  break;
3400 
3401  DS.SetRangeEnd(Tok.getLocation());
3402  ConsumeToken(); // The identifier
3403 
3404  // Objective-C supports type arguments and protocol references
3405  // following an Objective-C object or object pointer
3406  // type. Handle either one of them.
3407  if (Tok.is(tok::less) && getLangOpts().ObjC) {
3408  SourceLocation NewEndLoc;
3409  TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3410  Loc, TypeRep, /*consumeLastToken=*/true,
3411  NewEndLoc);
3412  if (NewTypeRep.isUsable()) {
3413  DS.UpdateTypeRep(NewTypeRep.get());
3414  DS.SetRangeEnd(NewEndLoc);
3415  }
3416  }
3417 
3418  // Need to support trailing type qualifiers (e.g. "id<p> const").
3419  // If a type specifier follows, it will be diagnosed elsewhere.
3420  continue;
3421  }
3422 
3423  // type-name
3424  case tok::annot_template_id: {
3425  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3426  if (TemplateId->Kind != TNK_Type_template &&
3427  TemplateId->Kind != TNK_Undeclared_template) {
3428  // This template-id does not refer to a type name, so we're
3429  // done with the type-specifiers.
3430  goto DoneWithDeclSpec;
3431  }
3432 
3433  // If we're in a context where the template-id could be a
3434  // constructor name or specialization, check whether this is a
3435  // constructor declaration.
3436  if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3437  Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3438  isConstructorDeclarator(TemplateId->SS.isEmpty()))
3439  goto DoneWithDeclSpec;
3440 
3441  // Turn the template-id annotation token into a type annotation
3442  // token, then try again to parse it as a type-specifier.
3443  AnnotateTemplateIdTokenAsType();
3444  continue;
3445  }
3446 
3447  // GNU attributes support.
3448  case tok::kw___attribute:
3449  ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3450  continue;
3451 
3452  // Microsoft declspec support.
3453  case tok::kw___declspec:
3454  ParseMicrosoftDeclSpecs(DS.getAttributes());
3455  continue;
3456 
3457  // Microsoft single token adornments.
3458  case tok::kw___forceinline: {
3459  isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3460  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3461  SourceLocation AttrNameLoc = Tok.getLocation();
3462  DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3463  nullptr, 0, ParsedAttr::AS_Keyword);
3464  break;
3465  }
3466 
3467  case tok::kw___unaligned:
3468  isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3469  getLangOpts());
3470  break;
3471 
3472  case tok::kw___sptr:
3473  case tok::kw___uptr:
3474  case tok::kw___ptr64:
3475  case tok::kw___ptr32:
3476  case tok::kw___w64:
3477  case tok::kw___cdecl:
3478  case tok::kw___stdcall:
3479  case tok::kw___fastcall:
3480  case tok::kw___thiscall:
3481  case tok::kw___regcall:
3482  case tok::kw___vectorcall:
3483  ParseMicrosoftTypeAttributes(DS.getAttributes());
3484  continue;
3485 
3486  // Borland single token adornments.
3487  case tok::kw___pascal:
3488  ParseBorlandTypeAttributes(DS.getAttributes());
3489  continue;
3490 
3491  // OpenCL single token adornments.
3492  case tok::kw___kernel:
3493  ParseOpenCLKernelAttributes(DS.getAttributes());
3494  continue;
3495 
3496  // Nullability type specifiers.
3497  case tok::kw__Nonnull:
3498  case tok::kw__Nullable:
3499  case tok::kw__Null_unspecified:
3500  ParseNullabilityTypeSpecifiers(DS.getAttributes());
3501  continue;
3502 
3503  // Objective-C 'kindof' types.
3504  case tok::kw___kindof:
3505  DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3506  nullptr, 0, ParsedAttr::AS_Keyword);
3507  (void)ConsumeToken();
3508  continue;
3509 
3510  // storage-class-specifier
3511  case tok::kw_typedef:
3512  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3513  PrevSpec, DiagID, Policy);
3514  isStorageClass = true;
3515  break;
3516  case tok::kw_extern:
3518  Diag(Tok, diag::ext_thread_before) << "extern";
3519  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3520  PrevSpec, DiagID, Policy);
3521  isStorageClass = true;
3522  break;
3523  case tok::kw___private_extern__:
3524  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3525  Loc, PrevSpec, DiagID, Policy);
3526  isStorageClass = true;
3527  break;
3528  case tok::kw_static:
3530  Diag(Tok, diag::ext_thread_before) << "static";
3531  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3532  PrevSpec, DiagID, Policy);
3533  isStorageClass = true;
3534  break;
3535  case tok::kw_auto:
3536  if (getLangOpts().CPlusPlus11) {
3537  if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3538  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3539  PrevSpec, DiagID, Policy);
3540  if (!isInvalid)
3541  Diag(Tok, diag::ext_auto_storage_class)
3543  } else
3544  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3545  DiagID, Policy);
3546  } else
3547  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3548  PrevSpec, DiagID, Policy);
3549  isStorageClass = true;
3550  break;
3551  case tok::kw___auto_type:
3552  Diag(Tok, diag::ext_auto_type);
3553  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3554  DiagID, Policy);
3555  break;
3556  case tok::kw_register:
3557  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3558  PrevSpec, DiagID, Policy);
3559  isStorageClass = true;
3560  break;
3561  case tok::kw_mutable:
3562  isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3563  PrevSpec, DiagID, Policy);
3564  isStorageClass = true;
3565  break;
3566  case tok::kw___thread:
3568  PrevSpec, DiagID);
3569  isStorageClass = true;
3570  break;
3571  case tok::kw_thread_local:
3573  PrevSpec, DiagID);
3574  isStorageClass = true;
3575  break;
3576  case tok::kw__Thread_local:
3577  if (!getLangOpts().C11)
3578  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3580  Loc, PrevSpec, DiagID);
3581  isStorageClass = true;
3582  break;
3583 
3584  // function-specifier
3585  case tok::kw_inline:
3586  isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3587  break;
3588  case tok::kw_virtual:
3589  // C++ for OpenCL does not allow virtual function qualifier, to avoid
3590  // function pointers restricted in OpenCL v2.0 s6.9.a.
3591  if (getLangOpts().OpenCLCPlusPlus) {
3592  DiagID = diag::err_openclcxx_virtual_function;
3593  PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3594  isInvalid = true;
3595  }
3596  else {
3597  isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3598  }
3599  break;
3600  case tok::kw_explicit: {
3601  SourceLocation ExplicitLoc = Loc;
3602  SourceLocation CloseParenLoc;
3603  ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3604  ConsumedEnd = ExplicitLoc;
3605  ConsumeToken(); // kw_explicit
3606  if (Tok.is(tok::l_paren)) {
3607  if (getLangOpts().CPlusPlus2a) {
3608  ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3609  BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3610  Tracker.consumeOpen();
3611  ExplicitExpr = ParseConstantExpression();
3612  ConsumedEnd = Tok.getLocation();
3613  if (ExplicitExpr.isUsable()) {
3614  CloseParenLoc = Tok.getLocation();
3615  Tracker.consumeClose();
3616  ExplicitSpec =
3617  Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3618  } else
3619  Tracker.skipToEnd();
3620  } else
3621  Diag(Tok.getLocation(), diag::warn_cxx2a_compat_explicit_bool);
3622  }
3623  isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3624  ExplicitSpec, CloseParenLoc);
3625  break;
3626  }
3627  case tok::kw__Noreturn:
3628  if (!getLangOpts().C11)
3629  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3630  isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3631  break;
3632 
3633  // alignment-specifier
3634  case tok::kw__Alignas:
3635  if (!getLangOpts().C11)
3636  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3637  ParseAlignmentSpecifier(DS.getAttributes());
3638  continue;
3639 
3640  // friend
3641  case tok::kw_friend:
3642  if (DSContext == DeclSpecContext::DSC_class)
3643  isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3644  else {
3645  PrevSpec = ""; // not actually used by the diagnostic
3646  DiagID = diag::err_friend_invalid_in_context;
3647  isInvalid = true;
3648  }
3649  break;
3650 
3651  // Modules
3652  case tok::kw___module_private__:
3653  isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3654  break;
3655 
3656  // constexpr, consteval, constinit specifiers
3657  case tok::kw_constexpr:
3658  isInvalid = DS.SetConstexprSpec(CSK_constexpr, Loc, PrevSpec, DiagID);
3659  break;
3660  case tok::kw_consteval:
3661  isInvalid = DS.SetConstexprSpec(CSK_consteval, Loc, PrevSpec, DiagID);
3662  break;
3663  case tok::kw_constinit:
3664  isInvalid = DS.SetConstexprSpec(CSK_constinit, Loc, PrevSpec, DiagID);
3665  break;
3666 
3667  // type-specifier
3668  case tok::kw_short:
3669  isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3670  DiagID, Policy);
3671  break;
3672  case tok::kw_long:
3674  isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3675  DiagID, Policy);
3676  else
3677  isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3678  DiagID, Policy);
3679  break;
3680  case tok::kw___int64:
3681  isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3682  DiagID, Policy);
3683  break;
3684  case tok::kw_signed:
3685  isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3686  DiagID);
3687  break;
3688  case tok::kw_unsigned:
3689  isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3690  DiagID);
3691  break;
3692  case tok::kw__Complex:
3693  if (!getLangOpts().C99)
3694  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3695  isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3696  DiagID);
3697  break;
3698  case tok::kw__Imaginary:
3699  if (!getLangOpts().C99)
3700  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3701  isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3702  DiagID);
3703  break;
3704  case tok::kw_void:
3705  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3706  DiagID, Policy);
3707  break;
3708  case tok::kw_char:
3709  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3710  DiagID, Policy);
3711  break;
3712  case tok::kw_int:
3713  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3714  DiagID, Policy);
3715  break;
3716  case tok::kw___int128:
3717  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3718  DiagID, Policy);
3719  break;
3720  case tok::kw_half:
3721  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3722  DiagID, Policy);
3723  break;
3724  case tok::kw_float:
3725  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3726  DiagID, Policy);
3727  break;
3728  case tok::kw_double:
3729  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3730  DiagID, Policy);
3731  break;
3732  case tok::kw__Float16:
3733  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3734  DiagID, Policy);
3735  break;
3736  case tok::kw__Accum:
3737  if (!getLangOpts().FixedPoint) {
3738  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3739  } else {
3740  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3741  DiagID, Policy);
3742  }
3743  break;
3744  case tok::kw__Fract:
3745  if (!getLangOpts().FixedPoint) {
3746  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3747  } else {
3748  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3749  DiagID, Policy);
3750  }
3751  break;
3752  case tok::kw__Sat:
3753  if (!getLangOpts().FixedPoint) {
3754  SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3755  } else {
3756  isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3757  }
3758  break;
3759  case tok::kw___float128:
3760  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3761  DiagID, Policy);
3762  break;
3763  case tok::kw_wchar_t:
3764  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3765  DiagID, Policy);
3766  break;
3767  case tok::kw_char8_t:
3768  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3769  DiagID, Policy);
3770  break;
3771  case tok::kw_char16_t:
3772  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3773  DiagID, Policy);
3774  break;
3775  case tok::kw_char32_t:
3776  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3777  DiagID, Policy);
3778  break;
3779  case tok::kw_bool:
3780  case tok::kw__Bool:
3781  if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
3782  Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3783 
3784  if (Tok.is(tok::kw_bool) &&
3787  PrevSpec = ""; // Not used by the diagnostic.
3788  DiagID = diag::err_bool_redeclaration;
3789  // For better error recovery.
3790  Tok.setKind(tok::identifier);
3791  isInvalid = true;
3792  } else {
3793  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3794  DiagID, Policy);
3795  }
3796  break;
3797  case tok::kw__Decimal32:
3798  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3799  DiagID, Policy);
3800  break;
3801  case tok::kw__Decimal64:
3802  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3803  DiagID, Policy);
3804  break;
3805  case tok::kw__Decimal128:
3806  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3807  DiagID, Policy);
3808  break;
3809  case tok::kw___vector:
3810  isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3811  break;
3812  case tok::kw___pixel:
3813  isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3814  break;
3815  case tok::kw___bool:
3816  isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3817  break;
3818  case tok::kw_pipe:
3819  if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
3820  !getLangOpts().OpenCLCPlusPlus)) {
3821  // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3822  // support the "pipe" word as identifier.
3823  Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3824  goto DoneWithDeclSpec;
3825  }
3826  isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3827  break;
3828 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3829  case tok::kw_##ImgType##_t: \
3830  isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3831  DiagID, Policy); \
3832  break;
3833 #include "clang/Basic/OpenCLImageTypes.def"
3834  case tok::kw___unknown_anytype:
3835  isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3836  PrevSpec, DiagID, Policy);
3837  break;
3838 
3839  // class-specifier:
3840  case tok::kw_class:
3841  case tok::kw_struct:
3842  case tok::kw___interface:
3843  case tok::kw_union: {
3844  tok::TokenKind Kind = Tok.getKind();
3845  ConsumeToken();
3846 
3847  // These are attributes following class specifiers.
3848  // To produce better diagnostic, we parse them when
3849  // parsing class specifier.
3850  ParsedAttributesWithRange Attributes(AttrFactory);
3851  ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3852  EnteringContext, DSContext, Attributes);
3853 
3854  // If there are attributes following class specifier,
3855  // take them over and handle them here.
3856  if (!Attributes.empty()) {
3857  AttrsLastTime = true;
3858  attrs.takeAllFrom(Attributes);
3859  }
3860  continue;
3861  }
3862 
3863  // enum-specifier:
3864  case tok::kw_enum:
3865  ConsumeToken();
3866  ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3867  continue;
3868 
3869  // cv-qualifier:
3870  case tok::kw_const:
3871  isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3872  getLangOpts());
3873  break;
3874  case tok::kw_volatile:
3875  isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3876  getLangOpts());
3877  break;
3878  case tok::kw_restrict:
3879  isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3880  getLangOpts());
3881  break;
3882 
3883  // C++ typename-specifier:
3884  case tok::kw_typename:
3886  DS.SetTypeSpecError();
3887  goto DoneWithDeclSpec;
3888  }
3889  if (!Tok.is(tok::kw_typename))
3890  continue;
3891  break;
3892 
3893  // GNU typeof support.
3894  case tok::kw_typeof:
3895  ParseTypeofSpecifier(DS);
3896  continue;
3897 
3898  case tok::annot_decltype:
3899  ParseDecltypeSpecifier(DS);
3900  continue;
3901 
3902  case tok::annot_pragma_pack:
3903  HandlePragmaPack();
3904  continue;
3905 
3906  case tok::annot_pragma_ms_pragma:
3907  HandlePragmaMSPragma();
3908  continue;
3909 
3910  case tok::annot_pragma_ms_vtordisp:
3911  HandlePragmaMSVtorDisp();
3912  continue;
3913 
3914  case tok::annot_pragma_ms_pointers_to_members:
3915  HandlePragmaMSPointersToMembers();
3916  continue;
3917 
3918  case tok::kw___underlying_type:
3919  ParseUnderlyingTypeSpecifier(DS);
3920  continue;
3921 
3922  case tok::kw__Atomic:
3923  // C11 6.7.2.4/4:
3924  // If the _Atomic keyword is immediately followed by a left parenthesis,
3925  // it is interpreted as a type specifier (with a type name), not as a
3926  // type qualifier.
3927  if (!getLangOpts().C11)
3928  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3929 
3930  if (NextToken().is(tok::l_paren)) {
3931  ParseAtomicSpecifier(DS);
3932  continue;
3933  }
3934  isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3935  getLangOpts());
3936  break;
3937 
3938  // OpenCL address space qualifiers:
3939  case tok::kw___generic:
3940  // generic address space is introduced only in OpenCL v2.0
3941  // see OpenCL C Spec v2.0 s6.5.5
3942  if (Actions.getLangOpts().OpenCLVersion < 200 &&
3943  !Actions.getLangOpts().OpenCLCPlusPlus) {
3944  DiagID = diag::err_opencl_unknown_type_specifier;
3945  PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3946  isInvalid = true;
3947  break;
3948  };
3949  LLVM_FALLTHROUGH;
3950  case tok::kw_private:
3951  case tok::kw___private:
3952  case tok::kw___global:
3953  case tok::kw___local:
3954  case tok::kw___constant:
3955  // OpenCL access qualifiers:
3956  case tok::kw___read_only:
3957  case tok::kw___write_only:
3958  case tok::kw___read_write:
3959  ParseOpenCLQualifiers(DS.getAttributes());
3960  break;
3961 
3962  case tok::less:
3963  // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3964  // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
3965  // but we support it.
3966  if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
3967  goto DoneWithDeclSpec;
3968 
3969  SourceLocation StartLoc = Tok.getLocation();
3970  SourceLocation EndLoc;
3971  TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3972  if (Type.isUsable()) {
3973  if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3974  PrevSpec, DiagID, Type.get(),
3975  Actions.getASTContext().getPrintingPolicy()))
3976  Diag(StartLoc, DiagID) << PrevSpec;
3977 
3978  DS.SetRangeEnd(EndLoc);
3979  } else {
3980  DS.SetTypeSpecError();
3981  }
3982 
3983  // Need to support trailing type qualifiers (e.g. "id<p> const").
3984  // If a type specifier follows, it will be diagnosed elsewhere.
3985  continue;
3986  }
3987 
3988  DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
3989 
3990  // If the specifier wasn't legal, issue a diagnostic.
3991  if (isInvalid) {
3992  assert(PrevSpec && "Method did not return previous specifier!");
3993  assert(DiagID);
3994 
3995  if (DiagID == diag::ext_duplicate_declspec ||
3996  DiagID == diag::ext_warn_duplicate_declspec ||
3997  DiagID == diag::err_duplicate_declspec)
3998  Diag(Loc, DiagID) << PrevSpec
4000  SourceRange(Loc, DS.getEndLoc()));
4001  else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4002  Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
4003  << getLangOpts().getOpenCLVersionTuple().getAsString()
4004  << PrevSpec << isStorageClass;
4005  } else
4006  Diag(Loc, DiagID) << PrevSpec;
4007  }
4008 
4009  if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4010  // After an error the next token can be an annotation token.
4011  ConsumeAnyToken();
4012 
4013  AttrsLastTime = false;
4014  }
4015 }
4016 
4017 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4018 /// semicolon.
4019 ///
4020 /// Note that a struct declaration refers to a declaration in a struct,
4021 /// not to the declaration of a struct.
4022 ///
4023 /// struct-declaration:
4024 /// [C2x] attributes-specifier-seq[opt]
4025 /// specifier-qualifier-list struct-declarator-list
4026 /// [GNU] __extension__ struct-declaration
4027 /// [GNU] specifier-qualifier-list
4028 /// struct-declarator-list:
4029 /// struct-declarator
4030 /// struct-declarator-list ',' struct-declarator
4031 /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
4032 /// struct-declarator:
4033 /// declarator
4034 /// [GNU] declarator attributes[opt]
4035 /// declarator[opt] ':' constant-expression
4036 /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
4037 ///
4038 void Parser::ParseStructDeclaration(
4039  ParsingDeclSpec &DS,
4040  llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4041 
4042  if (Tok.is(tok::kw___extension__)) {
4043  // __extension__ silences extension warnings in the subexpression.
4044  ExtensionRAIIObject O(Diags); // Use RAII to do this.
4045  ConsumeToken();
4046  return ParseStructDeclaration(DS, FieldsCallback);
4047  }
4048 
4049  // Parse leading attributes.
4050  ParsedAttributesWithRange Attrs(AttrFactory);
4051  MaybeParseCXX11Attributes(Attrs);
4052  DS.takeAttributesFrom(Attrs);
4053 
4054  // Parse the common specifier-qualifiers-list piece.
4055  ParseSpecifierQualifierList(DS);
4056 
4057  // If there are no declarators, this is a free-standing declaration
4058  // specifier. Let the actions module cope with it.
4059  if (Tok.is(tok::semi)) {
4060  RecordDecl *AnonRecord = nullptr;
4061  Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4062  DS, AnonRecord);
4063  assert(!AnonRecord && "Did not expect anonymous struct or union here");
4064  DS.complete(TheDecl);
4065  return;
4066  }
4067 
4068  // Read struct-declarators until we find the semicolon.
4069  bool FirstDeclarator = true;
4070  SourceLocation CommaLoc;
4071  while (1) {
4072  ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4073  DeclaratorInfo.D.setCommaLoc(CommaLoc);
4074 
4075  // Attributes are only allowed here on successive declarators.
4076  if (!FirstDeclarator)
4077  MaybeParseGNUAttributes(DeclaratorInfo.D);
4078 
4079  /// struct-declarator: declarator
4080  /// struct-declarator: declarator[opt] ':' constant-expression
4081  if (Tok.isNot(tok::colon)) {
4082  // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4084  ParseDeclarator(DeclaratorInfo.D);
4085  } else
4086  DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4087 
4088  if (TryConsumeToken(tok::colon)) {
4090  if (Res.isInvalid())
4091  SkipUntil(tok::semi, StopBeforeMatch);
4092  else
4093  DeclaratorInfo.BitfieldSize = Res.get();
4094  }
4095 
4096  // If attributes exist after the declarator, parse them.
4097  MaybeParseGNUAttributes(DeclaratorInfo.D);
4098 
4099  // We're done with this declarator; invoke the callback.
4100  FieldsCallback(DeclaratorInfo);
4101 
4102  // If we don't have a comma, it is either the end of the list (a ';')
4103  // or an error, bail out.
4104  if (!TryConsumeToken(tok::comma, CommaLoc))
4105  return;
4106 
4107  FirstDeclarator = false;
4108  }
4109 }
4110 
4111 /// ParseStructUnionBody
4112 /// struct-contents:
4113 /// struct-declaration-list
4114 /// [EXT] empty
4115 /// [GNU] "struct-declaration-list" without terminatoring ';'
4116 /// struct-declaration-list:
4117 /// struct-declaration
4118 /// struct-declaration-list struct-declaration
4119 /// [OBC] '@' 'defs' '(' class-name ')'
4120 ///
4121 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4123  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4124  "parsing struct/union body");
4125  assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4126 
4127  BalancedDelimiterTracker T(*this, tok::l_brace);
4128  if (T.consumeOpen())
4129  return;
4130 
4131  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4132  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4133 
4134  SmallVector<Decl *, 32> FieldDecls;
4135 
4136  // While we still have something to read, read the declarations in the struct.
4137  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4138  Tok.isNot(tok::eof)) {
4139  // Each iteration of this loop reads one struct-declaration.
4140 
4141  // Check for extraneous top-level semicolon.
4142  if (Tok.is(tok::semi)) {
4143  ConsumeExtraSemi(InsideStruct, TagType);
4144  continue;
4145  }
4146 
4147  // Parse _Static_assert declaration.
4148  if (Tok.is(tok::kw__Static_assert)) {
4149  SourceLocation DeclEnd;
4150  ParseStaticAssertDeclaration(DeclEnd);
4151  continue;
4152  }
4153 
4154  if (Tok.is(tok::annot_pragma_pack)) {
4155  HandlePragmaPack();
4156  continue;
4157  }
4158 
4159  if (Tok.is(tok::annot_pragma_align)) {
4160  HandlePragmaAlign();
4161  continue;
4162  }
4163 
4164  if (Tok.is(tok::annot_pragma_openmp)) {
4165  // Result can be ignored, because it must be always empty.
4166  AccessSpecifier AS = AS_none;
4167  ParsedAttributesWithRange Attrs(AttrFactory);
4168  (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4169  continue;
4170  }
4171 
4172  if (tok::isPragmaAnnotation(Tok.getKind())) {
4173  Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4175  TagType, Actions.getASTContext().getPrintingPolicy());
4176  ConsumeAnnotationToken();
4177  continue;
4178  }
4179 
4180  if (!Tok.is(tok::at)) {
4181  auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4182  // Install the declarator into the current TagDecl.
4183  Decl *Field =
4184  Actions.ActOnField(getCurScope(), TagDecl,
4185  FD.D.getDeclSpec().getSourceRange().getBegin(),
4186  FD.D, FD.BitfieldSize);
4187  FieldDecls.push_back(Field);
4188  FD.complete(Field);
4189  };
4190 
4191  // Parse all the comma separated declarators.
4192  ParsingDeclSpec DS(*this);
4193  ParseStructDeclaration(DS, CFieldCallback);
4194  } else { // Handle @defs
4195  ConsumeToken();
4196  if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4197  Diag(Tok, diag::err_unexpected_at);
4198  SkipUntil(tok::semi);
4199  continue;
4200  }
4201  ConsumeToken();
4202  ExpectAndConsume(tok::l_paren);
4203  if (!Tok.is(tok::identifier)) {
4204  Diag(Tok, diag::err_expected) << tok::identifier;
4205  SkipUntil(tok::semi);
4206  continue;
4207  }
4208  SmallVector<Decl *, 16> Fields;
4209  Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4210  Tok.getIdentifierInfo(), Fields);
4211  FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4212  ConsumeToken();
4213  ExpectAndConsume(tok::r_paren);
4214  }
4215 
4216  if (TryConsumeToken(tok::semi))
4217  continue;
4218 
4219  if (Tok.is(tok::r_brace)) {
4220  ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4221  break;
4222  }
4223 
4224  ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4225  // Skip to end of block or statement to avoid ext-warning on extra ';'.
4226  SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4227  // If we stopped at a ';', eat it.
4228  TryConsumeToken(tok::semi);
4229  }
4230 
4231  T.consumeClose();
4232 
4233  ParsedAttributes attrs(AttrFactory);
4234  // If attributes exist after struct contents, parse them.
4235  MaybeParseGNUAttributes(attrs);
4236 
4237  Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4238  T.getOpenLocation(), T.getCloseLocation(), attrs);
4239  StructScope.Exit();
4240  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4241 }
4242 
4243 /// ParseEnumSpecifier
4244 /// enum-specifier: [C99 6.7.2.2]
4245 /// 'enum' identifier[opt] '{' enumerator-list '}'
4246 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4247 /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4248 /// '}' attributes[opt]
4249 /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4250 /// '}'
4251 /// 'enum' identifier
4252 /// [GNU] 'enum' attributes[opt] identifier
4253 ///
4254 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4255 /// [C++11] enum-head '{' enumerator-list ',' '}'
4256 ///
4257 /// enum-head: [C++11]
4258 /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4259 /// enum-key attribute-specifier-seq[opt] nested-name-specifier
4260 /// identifier enum-base[opt]
4261 ///
4262 /// enum-key: [C++11]
4263 /// 'enum'
4264 /// 'enum' 'class'
4265 /// 'enum' 'struct'
4266 ///
4267 /// enum-base: [C++11]
4268 /// ':' type-specifier-seq
4269 ///
4270 /// [C++] elaborated-type-specifier:
4271 /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
4272 ///
4273 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4274  const ParsedTemplateInfo &TemplateInfo,
4275  AccessSpecifier AS, DeclSpecContext DSC) {
4276  // Parse the tag portion of this.
4277  if (Tok.is(tok::code_completion)) {
4278  // Code completion for an enum name.
4279  Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4280  return cutOffParsing();
4281  }
4282 
4283  // If attributes exist after tag, parse them.
4284  ParsedAttributesWithRange attrs(AttrFactory);
4285  MaybeParseGNUAttributes(attrs);
4286  MaybeParseCXX11Attributes(attrs);
4287  MaybeParseMicrosoftDeclSpecs(attrs);
4288 
4289  SourceLocation ScopedEnumKWLoc;
4290  bool IsScopedUsingClassTag = false;
4291 
4292  // In C++11, recognize 'enum class' and 'enum struct'.
4293  if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4294  Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4295  : diag::ext_scoped_enum);
4296  IsScopedUsingClassTag = Tok.is(tok::kw_class);
4297  ScopedEnumKWLoc = ConsumeToken();
4298 
4299  // Attributes are not allowed between these keywords. Diagnose,
4300  // but then just treat them like they appeared in the right place.
4301  ProhibitAttributes(attrs);
4302 
4303  // They are allowed afterwards, though.
4304  MaybeParseGNUAttributes(attrs);
4305  MaybeParseCXX11Attributes(attrs);
4306  MaybeParseMicrosoftDeclSpecs(attrs);
4307  }
4308 
4309  // C++11 [temp.explicit]p12:
4310  // The usual access controls do not apply to names used to specify
4311  // explicit instantiations.
4312  // We extend this to also cover explicit specializations. Note that
4313  // we don't suppress if this turns out to be an elaborated type
4314  // specifier.
4315  bool shouldDelayDiagsInTag =
4316  (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4317  TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4318  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4319 
4320  // Enum definitions should not be parsed in a trailing-return-type.
4321  bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
4322 
4323  CXXScopeSpec &SS = DS.getTypeSpecScope();
4324  if (getLangOpts().CPlusPlus) {
4325  // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4326  // if a fixed underlying type is allowed.
4327  ColonProtectionRAIIObject X(*this, AllowDeclaration);
4328 
4329  CXXScopeSpec Spec;
4330  if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4331  /*EnteringContext=*/true))
4332  return;
4333 
4334  if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4335  Diag(Tok, diag::err_expected) << tok::identifier;
4336  if (Tok.isNot(tok::l_brace)) {
4337  // Has no name and is not a definition.
4338  // Skip the rest of this declarator, up until the comma or semicolon.
4339  SkipUntil(tok::comma, StopAtSemi);
4340  return;
4341  }
4342  }
4343 
4344  SS = Spec;
4345  }
4346 
4347  // Must have either 'enum name' or 'enum {...}'.
4348  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4349  !(AllowDeclaration && Tok.is(tok::colon))) {
4350  Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4351 
4352  // Skip the rest of this declarator, up until the comma or semicolon.
4353  SkipUntil(tok::comma, StopAtSemi);
4354  return;
4355  }
4356 
4357  // If an identifier is present, consume and remember it.
4358  IdentifierInfo *Name = nullptr;
4359  SourceLocation NameLoc;
4360  if (Tok.is(tok::identifier)) {
4361  Name = Tok.getIdentifierInfo();
4362  NameLoc = ConsumeToken();
4363  }
4364 
4365  if (!Name && ScopedEnumKWLoc.isValid()) {
4366  // C++0x 7.2p2: The optional identifier shall not be omitted in the
4367  // declaration of a scoped enumeration.
4368  Diag(Tok, diag::err_scoped_enum_missing_identifier);
4369  ScopedEnumKWLoc = SourceLocation();
4370  IsScopedUsingClassTag = false;
4371  }
4372 
4373  // Okay, end the suppression area. We'll decide whether to emit the
4374  // diagnostics in a second.
4375  if (shouldDelayDiagsInTag)
4376  diagsFromTag.done();
4377 
4378  TypeResult BaseType;
4379 
4380  // Parse the fixed underlying type.
4381  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4382  if (AllowDeclaration && Tok.is(tok::colon)) {
4383  bool PossibleBitfield = false;
4384  if (CanBeBitfield) {
4385  // If we're in class scope, this can either be an enum declaration with
4386  // an underlying type, or a declaration of a bitfield member. We try to
4387  // use a simple disambiguation scheme first to catch the common cases
4388  // (integer literal, sizeof); if it's still ambiguous, we then consider
4389  // anything that's a simple-type-specifier followed by '(' as an
4390  // expression. This suffices because function types are not valid
4391  // underlying types anyway.
4394  TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4395  // If the next token starts an expression, we know we're parsing a
4396  // bit-field. This is the common case.
4397  if (TPR == TPResult::True)
4398  PossibleBitfield = true;
4399  // If the next token starts a type-specifier-seq, it may be either a
4400  // a fixed underlying type or the start of a function-style cast in C++;
4401  // lookahead one more token to see if it's obvious that we have a
4402  // fixed underlying type.
4403  else if (TPR == TPResult::False &&
4404  GetLookAheadToken(2).getKind() == tok::semi) {
4405  // Consume the ':'.
4406  ConsumeToken();
4407  } else {
4408  // We have the start of a type-specifier-seq, so we have to perform
4409  // tentative parsing to determine whether we have an expression or a
4410  // type.
4411  TentativeParsingAction TPA(*this);
4412 
4413  // Consume the ':'.
4414  ConsumeToken();
4415 
4416  // If we see a type specifier followed by an open-brace, we have an
4417  // ambiguity between an underlying type and a C++11 braced
4418  // function-style cast. Resolve this by always treating it as an
4419  // underlying type.
4420  // FIXME: The standard is not entirely clear on how to disambiguate in
4421  // this case.
4422  if ((getLangOpts().CPlusPlus &&
4423  isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4424  (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4425  // We'll parse this as a bitfield later.
4426  PossibleBitfield = true;
4427  TPA.Revert();
4428  } else {
4429  // We have a type-specifier-seq.
4430  TPA.Commit();
4431  }
4432  }
4433  } else {
4434  // Consume the ':'.
4435  ConsumeToken();
4436  }
4437 
4438  if (!PossibleBitfield) {
4439  SourceRange Range;
4440  BaseType = ParseTypeName(&Range);
4441 
4442  if (!getLangOpts().ObjC) {
4443  if (getLangOpts().CPlusPlus11)
4444  Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4445  else if (getLangOpts().CPlusPlus)
4446  Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4447  else if (getLangOpts().MicrosoftExt)
4448  Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
4449  else
4450  Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
4451  }
4452  }
4453  }
4454 
4455  // There are four options here. If we have 'friend enum foo;' then this is a
4456  // friend declaration, and cannot have an accompanying definition. If we have
4457  // 'enum foo;', then this is a forward declaration. If we have
4458  // 'enum foo {...' then this is a definition. Otherwise we have something
4459  // like 'enum foo xyz', a reference.
4460  //
4461  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4462  // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
4463  // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
4464  //
4465  Sema::TagUseKind TUK;
4466  if (!AllowDeclaration) {
4467  TUK = Sema::TUK_Reference;
4468  } else if (Tok.is(tok::l_brace)) {
4469  if (DS.isFriendSpecified()) {
4470  Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4471  << SourceRange(DS.getFriendSpecLoc());
4472  ConsumeBrace();
4473  SkipUntil(tok::r_brace, StopAtSemi);
4474  TUK = Sema::TUK_Friend;
4475  } else {
4476  TUK = Sema::TUK_Definition;
4477  }
4478  } else if (!isTypeSpecifier(DSC) &&
4479  (Tok.is(tok::semi) ||
4480  (Tok.isAtStartOfLine() &&
4481  !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4483  if (Tok.isNot(tok::semi)) {
4484  // A semicolon was missing after this declaration. Diagnose and recover.
4485  ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4486  PP.EnterToken(Tok, /*IsReinject=*/true);
4487  Tok.setKind(tok::semi);
4488  }
4489  } else {
4490  TUK = Sema::TUK_Reference;
4491  }
4492 
4493  // If this is an elaborated type specifier, and we delayed
4494  // diagnostics before, just merge them into the current pool.
4495  if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4496  diagsFromTag.redelay();
4497  }
4498 
4499  MultiTemplateParamsArg TParams;
4500  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4501  TUK != Sema::TUK_Reference) {
4502  if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4503  // Skip the rest of this declarator, up until the comma or semicolon.
4504  Diag(Tok, diag::err_enum_template);
4505  SkipUntil(tok::comma, StopAtSemi);
4506  return;
4507  }
4508 
4509  if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4510  // Enumerations can't be explicitly instantiated.
4511  DS.SetTypeSpecError();
4512  Diag(StartLoc, diag::err_explicit_instantiation_enum);
4513  return;
4514  }
4515 
4516  assert(TemplateInfo.TemplateParams && "no template parameters");
4517  TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4518  TemplateInfo.TemplateParams->size());
4519  }
4520 
4521  if (TUK == Sema::TUK_Reference)
4522  ProhibitAttributes(attrs);
4523 
4524  if (!Name && TUK != Sema::TUK_Definition) {
4525  Diag(Tok, diag::err_enumerator_unnamed_no_def);
4526 
4527  // Skip the rest of this declarator, up until the comma or semicolon.
4528  SkipUntil(tok::comma, StopAtSemi);
4529  return;
4530  }
4531 
4532  stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4533 
4534  Sema::SkipBodyInfo SkipBody;
4535  if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4536  NextToken().is(tok::identifier))
4537  SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4538  NextToken().getIdentifierInfo(),
4539  NextToken().getLocation());
4540 
4541  bool Owned = false;
4542  bool IsDependent = false;
4543  const char *PrevSpec = nullptr;
4544  unsigned DiagID;
4545  Decl *TagDecl = Actions.ActOnTag(
4546  getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4547  attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4548  ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4549  DSC == DeclSpecContext::DSC_type_specifier,
4550  DSC == DeclSpecContext::DSC_template_param ||
4551  DSC == DeclSpecContext::DSC_template_type_arg,
4552  &SkipBody);
4553 
4554  if (SkipBody.ShouldSkip) {
4555  assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4556 
4557  BalancedDelimiterTracker T(*this, tok::l_brace);
4558  T.consumeOpen();
4559  T.skipToEnd();
4560 
4561  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4562  NameLoc.isValid() ? NameLoc : StartLoc,
4563  PrevSpec, DiagID, TagDecl, Owned,
4564  Actions.getASTContext().getPrintingPolicy()))
4565  Diag(StartLoc, DiagID) << PrevSpec;
4566  return;
4567  }
4568 
4569  if (IsDependent) {
4570  // This enum has a dependent nested-name-specifier. Handle it as a
4571  // dependent tag.
4572  if (!Name) {
4573  DS.SetTypeSpecError();
4574  Diag(Tok, diag::err_expected_type_name_after_typename);
4575  return;
4576  }
4577 
4578  TypeResult Type = Actions.ActOnDependentTag(
4579  getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4580  if (Type.isInvalid()) {
4581  DS.SetTypeSpecError();
4582  return;
4583  }
4584 
4585  if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4586  NameLoc.isValid() ? NameLoc : StartLoc,
4587  PrevSpec, DiagID, Type.get(),
4588  Actions.getASTContext().getPrintingPolicy()))
4589  Diag(StartLoc, DiagID) << PrevSpec;
4590 
4591  return;
4592  }
4593 
4594  if (!TagDecl) {
4595  // The action failed to produce an enumeration tag. If this is a
4596  // definition, consume the entire definition.
4597  if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4598  ConsumeBrace();
4599  SkipUntil(tok::r_brace, StopAtSemi);
4600  }
4601 
4602  DS.SetTypeSpecError();
4603  return;
4604  }
4605 
4606  if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4607  Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4608  ParseEnumBody(StartLoc, D);
4609  if (SkipBody.CheckSameAsPrevious &&
4610  !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4611  DS.SetTypeSpecError();
4612  return;
4613  }
4614  }
4615 
4616  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4617  NameLoc.isValid() ? NameLoc : StartLoc,
4618  PrevSpec, DiagID, TagDecl, Owned,
4619  Actions.getASTContext().getPrintingPolicy()))
4620  Diag(StartLoc, DiagID) << PrevSpec;
4621 }
4622 
4623 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4624 /// enumerator-list:
4625 /// enumerator
4626 /// enumerator-list ',' enumerator
4627 /// enumerator:
4628 /// enumeration-constant attributes[opt]
4629 /// enumeration-constant attributes[opt] '=' constant-expression
4630 /// enumeration-constant:
4631 /// identifier
4632 ///
4633 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4634  // Enter the scope of the enum body and start the definition.
4635  ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4636  Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4637 
4638  BalancedDelimiterTracker T(*this, tok::l_brace);
4639  T.consumeOpen();
4640 
4641  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4642  if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4643  Diag(Tok, diag::err_empty_enum);
4644 
4645  SmallVector<Decl *, 32> EnumConstantDecls;
4646  SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4647 
4648  Decl *LastEnumConstDecl = nullptr;
4649 
4650  // Parse the enumerator-list.
4651  while (Tok.isNot(tok::r_brace)) {
4652  // Parse enumerator. If failed, try skipping till the start of the next
4653  // enumerator definition.
4654  if (Tok.isNot(tok::identifier)) {
4655  Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4656  if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4657  TryConsumeToken(tok::comma))
4658  continue;
4659  break;
4660  }
4661  IdentifierInfo *Ident = Tok.getIdentifierInfo();
4662  SourceLocation IdentLoc = ConsumeToken();
4663 
4664  // If attributes exist after the enumerator, parse them.
4665  ParsedAttributesWithRange attrs(AttrFactory);
4666  MaybeParseGNUAttributes(attrs);
4667  ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4668  if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4669  if (getLangOpts().CPlusPlus)
4670  Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4671  ? diag::warn_cxx14_compat_ns_enum_attribute
4672  : diag::ext_ns_enum_attribute)
4673  << 1 /*enumerator*/;
4674  ParseCXX11Attributes(attrs);
4675  }
4676 
4677  SourceLocation EqualLoc;
4678  ExprResult AssignedVal;
4679  EnumAvailabilityDiags.emplace_back(*this);
4680 
4681  if (TryConsumeToken(tok::equal, EqualLoc)) {
4682  AssignedVal = ParseConstantExpression();
4683  if (AssignedVal.isInvalid())
4684  SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4685  }
4686 
4687  // Install the enumerator constant into EnumDecl.
4688  Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4689  getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4690  EqualLoc, AssignedVal.get());
4691  EnumAvailabilityDiags.back().done();
4692 
4693  EnumConstantDecls.push_back(EnumConstDecl);
4694  LastEnumConstDecl = EnumConstDecl;
4695 
4696  if (Tok.is(tok::identifier)) {
4697  // We're missing a comma between enumerators.
4699  Diag(Loc, diag::err_enumerator_list_missing_comma)
4700  << FixItHint::CreateInsertion(Loc, ", ");
4701  continue;
4702  }
4703 
4704  // Emumerator definition must be finished, only comma or r_brace are
4705  // allowed here.
4706  SourceLocation CommaLoc;
4707  if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4708  if (EqualLoc.isValid())
4709  Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4710  << tok::comma;
4711  else
4712  Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4713  if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4714  if (TryConsumeToken(tok::comma, CommaLoc))
4715  continue;
4716  } else {
4717  break;
4718  }
4719  }
4720 
4721  // If comma is followed by r_brace, emit appropriate warning.
4722  if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4723  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4724  Diag(CommaLoc, getLangOpts().CPlusPlus ?
4725  diag::ext_enumerator_list_comma_cxx :
4726  diag::ext_enumerator_list_comma_c)
4727  << FixItHint::CreateRemoval(CommaLoc);
4728  else if (getLangOpts().CPlusPlus11)
4729  Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4730  << FixItHint::CreateRemoval(CommaLoc);
4731  break;
4732  }
4733  }
4734 
4735  // Eat the }.
4736  T.consumeClose();
4737 
4738  // If attributes exist after the identifier list, parse them.
4739  ParsedAttributes attrs(AttrFactory);
4740  MaybeParseGNUAttributes(attrs);
4741 
4742  Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4743  getCurScope(), attrs);
4744 
4745  // Now handle enum constant availability diagnostics.
4746  assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4747  for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4749  EnumAvailabilityDiags[i].redelay();
4750  PD.complete(EnumConstantDecls[i]);
4751  }
4752 
4753  EnumScope.Exit();
4754  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4755 
4756  // The next token must be valid after an enum definition. If not, a ';'
4757  // was probably forgotten.
4758  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4759  if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4760  ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4761  // Push this token back into the preprocessor and change our current token
4762  // to ';' so that the rest of the code recovers as though there were an
4763  // ';' after the definition.
4764  PP.EnterToken(Tok, /*IsReinject=*/true);
4765  Tok.setKind(tok::semi);
4766  }
4767 }
4768 
4769 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4770 /// is definitely a type-specifier. Return false if it isn't part of a type
4771 /// specifier or if we're not sure.
4772 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4773  switch (Tok.getKind()) {
4774  default: return false;
4775  // type-specifiers
4776  case tok::kw_short:
4777  case tok::kw_long:
4778  case tok::kw___int64:
4779  case tok::kw___int128:
4780  case tok::kw_signed:
4781  case tok::kw_unsigned:
4782  case tok::kw__Complex:
4783  case tok::kw__Imaginary:
4784  case tok::kw_void:
4785  case tok::kw_char:
4786  case tok::kw_wchar_t:
4787  case tok::kw_char8_t:
4788  case tok::kw_char16_t:
4789  case tok::kw_char32_t:
4790  case tok::kw_int:
4791  case tok::kw_half:
4792  case tok::kw_float:
4793  case tok::kw_double:
4794  case tok::kw__Accum:
4795  case tok::kw__Fract:
4796  case tok::kw__Float16:
4797  case tok::kw___float128:
4798  case tok::kw_bool:
4799  case tok::kw__Bool:
4800  case tok::kw__Decimal32:
4801  case tok::kw__Decimal64:
4802  case tok::kw__Decimal128:
4803  case tok::kw___vector:
4804 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4805 #include "clang/Basic/OpenCLImageTypes.def"
4806 
4807  // struct-or-union-specifier (C99) or class-specifier (C++)
4808  case tok::kw_class:
4809  case tok::kw_struct:
4810  case tok::kw___interface:
4811  case tok::kw_union:
4812  // enum-specifier
4813  case tok::kw_enum:
4814 
4815  // typedef-name
4816  case tok::annot_typename:
4817  return true;
4818  }
4819 }
4820 
4821 /// isTypeSpecifierQualifier - Return true if the current token could be the
4822 /// start of a specifier-qualifier-list.
4823 bool Parser::isTypeSpecifierQualifier() {
4824  switch (Tok.getKind()) {
4825  default: return false;
4826 
4827  case tok::identifier: // foo::bar
4828  if (TryAltiVecVectorToken())
4829  return true;
4830  LLVM_FALLTHROUGH;
4831  case tok::kw_typename: // typename T::type
4832  // Annotate typenames and C++ scope specifiers. If we get one, just
4833  // recurse to handle whatever we get.
4835  return true;
4836  if (Tok.is(tok::identifier))
4837  return false;
4838  return isTypeSpecifierQualifier();
4839 
4840  case tok::coloncolon: // ::foo::bar
4841  if (NextToken().is(tok::kw_new) || // ::new
4842  NextToken().is(tok::kw_delete)) // ::delete
4843  return false;
4844 
4846  return true;
4847  return isTypeSpecifierQualifier();
4848 
4849  // GNU attributes support.
4850  case tok::kw___attribute:
4851  // GNU typeof support.
4852  case tok::kw_typeof:
4853 
4854  // type-specifiers
4855  case tok::kw_short:
4856  case tok::kw_long:
4857  case tok::kw___int64:
4858  case tok::kw___int128:
4859  case tok::kw_signed:
4860  case tok::kw_unsigned:
4861  case tok::kw__Complex:
4862  case tok::kw__Imaginary:
4863  case tok::kw_void:
4864  case tok::kw_char:
4865  case tok::kw_wchar_t:
4866  case tok::kw_char8_t:
4867  case tok::kw_char16_t:
4868  case tok::kw_char32_t:
4869  case tok::kw_int:
4870  case tok::kw_half:
4871  case tok::kw_float:
4872  case tok::kw_double:
4873  case tok::kw__Accum:
4874  case tok::kw__Fract:
4875  case tok::kw__Float16:
4876  case tok::kw___float128:
4877  case tok::kw_bool:
4878  case tok::kw__Bool:
4879  case tok::kw__Decimal32:
4880  case tok::kw__Decimal64:
4881  case tok::kw__Decimal128:
4882  case tok::kw___vector:
4883 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4884 #include "clang/Basic/OpenCLImageTypes.def"
4885 
4886  // struct-or-union-specifier (C99) or class-specifier (C++)
4887  case tok::kw_class:
4888  case tok::kw_struct:
4889  case tok::kw___interface:
4890  case tok::kw_union:
4891  // enum-specifier
4892  case tok::kw_enum:
4893 
4894  // type-qualifier
4895  case tok::kw_const:
4896  case tok::kw_volatile:
4897  case tok::kw_restrict:
4898  case tok::kw__Sat:
4899 
4900  // Debugger support.
4901  case tok::kw___unknown_anytype:
4902 
4903  // typedef-name
4904  case tok::annot_typename:
4905  return true;
4906 
4907  // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4908  case tok::less:
4909  return getLangOpts().ObjC;
4910 
4911  case tok::kw___cdecl:
4912  case tok::kw___stdcall:
4913  case tok::kw___fastcall:
4914  case tok::kw___thiscall:
4915  case tok::kw___regcall:
4916  case tok::kw___vectorcall:
4917  case tok::kw___w64:
4918  case tok::kw___ptr64:
4919  case tok::kw___ptr32:
4920  case tok::kw___pascal:
4921  case tok::kw___unaligned:
4922 
4923  case tok::kw__Nonnull:
4924  case tok::kw__Nullable:
4925  case tok::kw__Null_unspecified:
4926 
4927  case tok::kw___kindof:
4928 
4929  case tok::kw___private:
4930  case tok::kw___local:
4931  case tok::kw___global:
4932  case tok::kw___constant:
4933  case tok::kw___generic:
4934  case tok::kw___read_only:
4935  case tok::kw___read_write:
4936  case tok::kw___write_only:
4937  return true;
4938 
4939  case tok::kw_private:
4940  return getLangOpts().OpenCL;
4941 
4942  // C11 _Atomic
4943  case tok::kw__Atomic:
4944  return true;
4945  }
4946 }
4947 
4948 /// isDeclarationSpecifier() - Return true if the current token is part of a
4949 /// declaration specifier.
4950 ///
4951 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4952 /// this check is to disambiguate between an expression and a declaration.
4953 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4954  switch (Tok.getKind()) {
4955  default: return false;
4956 
4957  case tok::kw_pipe:
4958  return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
4959  getLangOpts().OpenCLCPlusPlus;
4960 
4961  case tok::identifier: // foo::bar
4962  // Unfortunate hack to support "Class.factoryMethod" notation.
4963  if (getLangOpts().ObjC && NextToken().is(tok::period))
4964  return false;
4965  if (TryAltiVecVectorToken())
4966  return true;
4967  LLVM_FALLTHROUGH;
4968  case tok::kw_decltype: // decltype(T())::type
4969  case tok::kw_typename: // typename T::type
4970  // Annotate typenames and C++ scope specifiers. If we get one, just
4971  // recurse to handle whatever we get.
4973  return true;
4974  if (Tok.is(tok::identifier))
4975  return false;
4976 
4977  // If we're in Objective-C and we have an Objective-C class type followed
4978  // by an identifier and then either ':' or ']', in a place where an
4979  // expression is permitted, then this is probably a class message send
4980  // missing the initial '['. In this case, we won't consider this to be
4981  // the start of a declaration.
4982  if (DisambiguatingWithExpression &&
4983  isStartOfObjCClassMessageMissingOpenBracket())
4984  return false;
4985 
4986  return isDeclarationSpecifier();
4987 
4988  case tok::coloncolon: // ::foo::bar
4989  if (NextToken().is(tok::kw_new) || // ::new
4990  NextToken().is(tok::kw_delete)) // ::delete
4991  return false;
4992 
4993  // Annotate typenames and C++ scope specifiers. If we get one, just
4994  // recurse to handle whatever we get.
4996  return true;
4997  return isDeclarationSpecifier();
4998 
4999  // storage-class-specifier
5000  case tok::kw_typedef:
5001  case tok::kw_extern:
5002  case tok::kw___private_extern__:
5003  case tok::kw_static:
5004  case tok::kw_auto:
5005  case tok::kw___auto_type:
5006  case tok::kw_register:
5007  case tok::kw___thread:
5008  case tok::kw_thread_local:
5009  case tok::kw__Thread_local:
5010 
5011  // Modules
5012  case tok::kw___module_private__:
5013 
5014  // Debugger support
5015  case tok::kw___unknown_anytype:
5016 
5017  // type-specifiers
5018  case tok::kw_short:
5019  case tok::kw_long:
5020  case tok::kw___int64:
5021  case tok::kw___int128:
5022  case tok::kw_signed:
5023  case tok::kw_unsigned:
5024  case tok::kw__Complex:
5025  case tok::kw__Imaginary:
5026  case tok::kw_void:
5027  case tok::kw_char:
5028  case tok::kw_wchar_t:
5029  case tok::kw_char8_t:
5030  case tok::kw_char16_t:
5031  case tok::kw_char32_t:
5032 
5033  case tok::kw_int:
5034  case tok::kw_half:
5035  case tok::kw_float:
5036  case tok::kw_double:
5037  case tok::kw__Accum:
5038  case tok::kw__Fract:
5039  case tok::kw__Float16:
5040  case tok::kw___float128:
5041  case tok::kw_bool:
5042  case tok::kw__Bool:
5043  case tok::kw__Decimal32:
5044  case tok::kw__Decimal64:
5045  case tok::kw__Decimal128:
5046  case tok::kw___vector:
5047 
5048  // struct-or-union-specifier (C99) or class-specifier (C++)
5049  case tok::kw_class:
5050  case tok::kw_struct:
5051  case tok::kw_union:
5052  case tok::kw___interface:
5053  // enum-specifier
5054  case tok::kw_enum:
5055 
5056  // type-qualifier
5057  case tok::kw_const:
5058  case tok::kw_volatile:
5059  case tok::kw_restrict:
5060  case tok::kw__Sat:
5061 
5062  // function-specifier
5063  case tok::kw_inline:
5064  case tok::kw_virtual:
5065  case tok::kw_explicit:
5066  case tok::kw__Noreturn:
5067 
5068  // alignment-specifier
5069  case tok::kw__Alignas:
5070 
5071  // friend keyword.
5072  case tok::kw_friend:
5073 
5074  // static_assert-declaration
5075  case tok::kw__Static_assert:
5076 
5077  // GNU typeof support.
5078  case tok::kw_typeof:
5079 
5080  // GNU attributes.
5081  case tok::kw___attribute:
5082 
5083  // C++11 decltype and constexpr.
5084  case tok::annot_decltype:
5085  case tok::kw_constexpr:
5086 
5087  // C++20 consteval and constinit.
5088  case tok::kw_consteval:
5089  case tok::kw_constinit:
5090 
5091  // C11 _Atomic
5092  case tok::kw__Atomic:
5093  return true;
5094 
5095  // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5096  case tok::less:
5097  return getLangOpts().ObjC;
5098 
5099  // typedef-name
5100  case tok::annot_typename:
5101  return !DisambiguatingWithExpression ||
5102  !isStartOfObjCClassMessageMissingOpenBracket();
5103 
5104  case tok::kw___declspec:
5105  case tok::kw___cdecl:
5106  case tok::kw___stdcall:
5107  case tok::kw___fastcall:
5108  case tok::kw___thiscall:
5109  case tok::kw___regcall:
5110  case tok::kw___vectorcall:
5111  case tok::kw___w64:
5112  case tok::kw___sptr:
5113  case tok::kw___uptr:
5114  case tok::kw___ptr64:
5115  case tok::kw___ptr32:
5116  case tok::kw___forceinline:
5117  case tok::kw___pascal:
5118  case tok::kw___unaligned:
5119 
5120  case tok::kw__Nonnull:
5121  case tok::kw__Nullable:
5122  case tok::kw__Null_unspecified:
5123 
5124  case tok::kw___kindof:
5125 
5126  case tok::kw___private:
5127  case tok::kw___local:
5128  case tok::kw___global:
5129  case tok::kw___constant:
5130  case tok::kw___generic:
5131  case tok::kw___read_only:
5132  case tok::kw___read_write:
5133  case tok::kw___write_only:
5134 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5135 #include "clang/Basic/OpenCLImageTypes.def"
5136 
5137  return true;
5138 
5139  case tok::kw_private:
5140  return getLangOpts().OpenCL;
5141  }
5142 }
5143 
5144 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
5145  TentativeParsingAction TPA(*this);
5146 
5147  // Parse the C++ scope specifier.
5148  CXXScopeSpec SS;
5149  if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
5150  /*EnteringContext=*/true)) {
5151  TPA.Revert();
5152  return false;
5153  }
5154 
5155  // Parse the constructor name.
5156  if (Tok.is(tok::identifier)) {
5157  // We already know that we have a constructor name; just consume
5158  // the token.
5159  ConsumeToken();
5160  } else if (Tok.is(tok::annot_template_id)) {
5161  ConsumeAnnotationToken();
5162  } else {
5163  TPA.Revert();
5164  return false;
5165  }
5166 
5167  // There may be attributes here, appertaining to the constructor name or type
5168  // we just stepped past.
5169  SkipCXX11Attributes();
5170 
5171  // Current class name must be followed by a left parenthesis.
5172  if (Tok.isNot(tok::l_paren)) {
5173  TPA.Revert();
5174  return false;
5175  }
5176  ConsumeParen();
5177 
5178  // A right parenthesis, or ellipsis followed by a right parenthesis signals
5179  // that we have a constructor.
5180  if (Tok.is(tok::r_paren) ||
5181  (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5182  TPA.Revert();
5183  return true;
5184  }
5185 
5186  // A C++11 attribute here signals that we have a constructor, and is an
5187  // attribute on the first constructor parameter.
5188  if (getLangOpts().CPlusPlus11 &&
5189  isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5190  /*OuterMightBeMessageSend*/ true)) {
5191  TPA.Revert();
5192  return true;
5193  }
5194 
5195  // If we need to, enter the specified scope.
5196  DeclaratorScopeObj DeclScopeObj(*this, SS);
5197  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5198  DeclScopeObj.EnterDeclaratorScope();
5199 
5200  // Optionally skip Microsoft attributes.
5201  ParsedAttributes Attrs(AttrFactory);
5202  MaybeParseMicrosoftAttributes(Attrs);
5203 
5204  // Check whether the next token(s) are part of a declaration
5205  // specifier, in which case we have the start of a parameter and,
5206  // therefore, we know that this is a constructor.
5207  bool IsConstructor = false;
5208  if (isDeclarationSpecifier())
5209  IsConstructor = true;
5210  else if (Tok.is(tok::identifier) ||
5211  (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5212  // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5213  // This might be a parenthesized member name, but is more likely to
5214  // be a constructor declaration with an invalid argument type. Keep
5215  // looking.
5216  if (Tok.is(tok::annot_cxxscope))
5217  ConsumeAnnotationToken();
5218  ConsumeToken();
5219 
5220  // If this is not a constructor, we must be parsing a declarator,
5221  // which must have one of the following syntactic forms (see the
5222  // grammar extract at the start of ParseDirectDeclarator):
5223  switch (Tok.getKind()) {
5224  case tok::l_paren:
5225  // C(X ( int));
5226  case tok::l_square:
5227  // C(X [ 5]);
5228  // C(X [ [attribute]]);
5229  case tok::coloncolon:
5230  // C(X :: Y);
5231  // C(X :: *p);
5232  // Assume this isn't a constructor, rather than assuming it's a
5233  // constructor with an unnamed parameter of an ill-formed type.
5234  break;
5235 
5236  case tok::r_paren:
5237  // C(X )
5238 
5239  // Skip past the right-paren and any following attributes to get to
5240  // the function body or trailing-return-type.
5241  ConsumeParen();
5242  SkipCXX11Attributes();
5243 
5244  if (DeductionGuide) {
5245  // C(X) -> ... is a deduction guide.
5246  IsConstructor = Tok.is(tok::arrow);
5247  break;
5248  }
5249  if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5250  // Assume these were meant to be constructors:
5251  // C(X) : (the name of a bit-field cannot be parenthesized).
5252  // C(X) try (this is otherwise ill-formed).
5253  IsConstructor = true;
5254  }
5255  if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5256  // If we have a constructor name within the class definition,
5257  // assume these were meant to be constructors:
5258  // C(X) {
5259  // C(X) ;
5260  // ... because otherwise we would be declaring a non-static data
5261  // member that is ill-formed because it's of the same type as its
5262  // surrounding class.
5263  //
5264  // FIXME: We can actually do this whether or not the name is qualified,
5265  // because if it is qualified in this context it must be being used as
5266  // a constructor name.
5267  // currently, so we're somewhat conservative here.
5268  IsConstructor = IsUnqualified;
5269  }
5270  break;
5271 
5272  default:
5273  IsConstructor = true;
5274  break;
5275  }
5276  }
5277 
5278  TPA.Revert();
5279  return IsConstructor;
5280 }
5281 
5282 /// ParseTypeQualifierListOpt
5283 /// type-qualifier-list: [C99 6.7.5]
5284 /// type-qualifier
5285 /// [vendor] attributes
5286 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5287 /// type-qualifier-list type-qualifier
5288 /// [vendor] type-qualifier-list attributes
5289 /// [ only if AttrReqs & AR_VendorAttributesParsed ]
5290 /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
5291 /// [ only if AttReqs & AR_CXX11AttributesParsed ]
5292 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5293 /// AttrRequirements bitmask values.
5294 void Parser::ParseTypeQualifierListOpt(
5295  DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5296  bool IdentifierRequired,
5297  Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5298  if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5299  isCXX11AttributeSpecifier()) {
5300  ParsedAttributesWithRange attrs(AttrFactory);
5301  ParseCXX11Attributes(attrs);
5302  DS.takeAttributesFrom(attrs);
5303  }
5304 
5305  SourceLocation EndLoc;
5306 
5307  while (1) {
5308  bool isInvalid = false;
5309  const char *PrevSpec = nullptr;
5310  unsigned DiagID = 0;
5311  SourceLocation Loc = Tok.getLocation();
5312 
5313  switch (Tok.getKind()) {
5314  case tok::code_completion:
5316  (*CodeCompletionHandler)();
5317  else
5318  Actions.CodeCompleteTypeQualifiers(DS);
5319  return cutOffParsing();
5320 
5321  case tok::kw_const:
5322  isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
5323  getLangOpts());
5324  break;
5325  case tok::kw_volatile:
5326  isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5327  getLangOpts());
5328  break;
5329  case tok::kw_restrict:
5330  isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5331  getLangOpts());
5332  break;
5333  case tok::kw__Atomic:
5334  if (!AtomicAllowed)
5335  goto DoneWithTypeQuals;
5336  if (!getLangOpts().C11)
5337  Diag(Tok, diag::ext_c11_feature) << Tok.getName();
5338  isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5339  getLangOpts());
5340  break;
5341 
5342  // OpenCL qualifiers:
5343  case tok::kw_private:
5344  if (!getLangOpts().OpenCL)
5345  goto DoneWithTypeQuals;
5346  LLVM_FALLTHROUGH;
5347  case tok::kw___private:
5348  case tok::kw___global:
5349  case tok::kw___local:
5350  case tok::kw___constant:
5351  case tok::kw___generic:
5352  case tok::kw___read_only:
5353  case tok::kw___write_only:
5354  case tok::kw___read_write:
5355  ParseOpenCLQualifiers(DS.getAttributes());
5356  break;
5357 
5358  case tok::kw___unaligned:
5359  isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5360  getLangOpts());
5361  break;
5362  case tok::kw___uptr:
5363  // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5364  // with the MS modifier keyword.
5365  if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5366  IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5367  if (TryKeywordIdentFallback(false))
5368  continue;
5369  }
5370  LLVM_FALLTHROUGH;
5371  case tok::kw___sptr:
5372  case tok::kw___w64:
5373  case tok::kw___ptr64:
5374  case tok::kw___ptr32:
5375  case tok::kw___cdecl:
5376  case tok::kw___stdcall:
5377  case tok::kw___fastcall:
5378  case tok::kw___thiscall:
5379  case tok::kw___regcall:
5380  case tok::kw___vectorcall:
5381  if (AttrReqs & AR_DeclspecAttributesParsed) {
5382  ParseMicrosoftTypeAttributes(DS.getAttributes());
5383  continue;
5384  }
5385  goto DoneWithTypeQuals;
5386  case tok::kw___pascal:
5387  if (AttrReqs & AR_VendorAttributesParsed) {
5388  ParseBorlandTypeAttributes(DS.getAttributes());
5389  continue;
5390  }
5391  goto DoneWithTypeQuals;
5392 
5393  // Nullability type specifiers.
5394  case tok::kw__Nonnull:
5395  case tok::kw__Nullable:
5396  case tok::kw__Null_unspecified:
5397  ParseNullabilityTypeSpecifiers(DS.getAttributes());
5398  continue;
5399 
5400  // Objective-C 'kindof' types.
5401  case tok::kw___kindof:
5402  DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5403  nullptr, 0, ParsedAttr::AS_Keyword);
5404  (void)ConsumeToken();
5405  continue;
5406 
5407  case tok::kw___attribute:
5408  if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5409  // When GNU attributes are expressly forbidden, diagnose their usage.
5410  Diag(Tok, diag::err_attributes_not_allowed);
5411 
5412  // Parse the attributes even if they are rejected to ensure that error
5413  // recovery is graceful.
5414  if (AttrReqs & AR_GNUAttributesParsed ||
5415  AttrReqs & AR_GNUAttributesParsedAndRejected) {
5416  ParseGNUAttributes(DS.getAttributes());
5417  continue; // do *not* consume the next token!
5418  }
5419  // otherwise, FALL THROUGH!
5420  LLVM_FALLTHROUGH;
5421  default:
5422  DoneWithTypeQuals:
5423  // If this is not a type-qualifier token, we're done reading type
5424  // qualifiers. First verify that DeclSpec's are consistent.
5425  DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5426  if (EndLoc.isValid())
5427  DS.SetRangeEnd(EndLoc);
5428  return;
5429  }
5430 
5431  // If the specifier combination wasn't legal, issue a diagnostic.
5432  if (isInvalid) {
5433  assert(PrevSpec && "Method did not return previous specifier!");
5434  Diag(Tok, DiagID) << PrevSpec;
5435  }
5436  EndLoc = ConsumeToken();
5437  }
5438 }
5439 
5440 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5441 ///
5442 void Parser::ParseDeclarator(Declarator &D) {
5443  /// This implements the 'declarator' production in the C grammar, then checks
5444  /// for well-formedness and issues diagnostics.
5445  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5446 }
5447 
5449  DeclaratorContext TheContext) {
5450  if (Kind == tok::star || Kind == tok::caret)
5451  return true;
5452 
5453  if (Kind == tok::kw_pipe &&
5454  ((Lang.OpenCL && Lang.OpenCLVersion >= 200) || Lang.OpenCLCPlusPlus))
5455  return true;
5456 
5457  if (!Lang.CPlusPlus)
5458  return false;
5459 
5460  if (Kind == tok::amp)
5461  return true;
5462 
5463  // We parse rvalue refs in C++03, because otherwise the errors are scary.
5464  // But we must not parse them in conversion-type-ids and new-type-ids, since
5465  // those can be legitimately followed by a && operator.
5466  // (The same thing can in theory happen after a trailing-return-type, but
5467  // since those are a C++11 feature, there is no rejects-valid issue there.)
5468  if (Kind == tok::ampamp)
5469  return Lang.CPlusPlus11 ||
5470  (TheContext != DeclaratorContext::ConversionIdContext &&
5471  TheContext != DeclaratorContext::CXXNewContext);
5472 
5473  return false;
5474 }
5475 
5476 // Indicates whether the given declarator is a pipe declarator.
5477 static bool isPipeDeclerator(const Declarator &D) {
5478  const unsigned NumTypes = D.getNumTypeObjects();
5479 
5480  for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5482  return true;
5483 
5484  return false;
5485 }
5486 
5487 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5488 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5489 /// isn't parsed at all, making this function effectively parse the C++
5490 /// ptr-operator production.
5491 ///
5492 /// If the grammar of this construct is extended, matching changes must also be
5493 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5494 /// isConstructorDeclarator.
5495 ///
5496 /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5497 /// [C] pointer[opt] direct-declarator
5498 /// [C++] direct-declarator
5499 /// [C++] ptr-operator declarator
5500 ///
5501 /// pointer: [C99 6.7.5]
5502 /// '*' type-qualifier-list[opt]
5503 /// '*' type-qualifier-list[opt] pointer
5504 ///
5505 /// ptr-operator:
5506 /// '*' cv-qualifier-seq[opt]
5507 /// '&'
5508 /// [C++0x] '&&'
5509 /// [GNU] '&' restrict[opt] attributes[opt]
5510 /// [GNU?] '&&' restrict[opt] attributes[opt]
5511 /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5512 void Parser::ParseDeclaratorInternal(Declarator &D,
5513  DirectDeclParseFunction DirectDeclParser) {
5514  if (Diags.hasAllExtensionsSilenced())
5515  D.setExtension();
5516 
5517  // C++ member pointers start with a '::' or a nested-name.
5518  // Member pointers get special handling, since there's no place for the
5519  // scope spec in the generic path below.
5520  if (getLangOpts().CPlusPlus &&
5521  (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5522  (Tok.is(tok::identifier) &&
5523  (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5524  Tok.is(tok::annot_cxxscope))) {
5525  bool EnteringContext =
5528  CXXScopeSpec SS;
5529  ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5530 
5531  if (SS.isNotEmpty()) {
5532  if (Tok.isNot(tok::star)) {
5533  // The scope spec really belongs to the direct-declarator.
5534  if (D.mayHaveIdentifier())
5535  D.getCXXScopeSpec() = SS;
5536  else
5537  AnnotateScopeToken(SS, true);
5538 
5539  if (DirectDeclParser)
5540  (this->*DirectDeclParser)(D);
5541  return;
5542  }
5543 
5544  SourceLocation Loc = ConsumeToken();
5545  D.SetRangeEnd(Loc);
5546  DeclSpec DS(AttrFactory);
5547  ParseTypeQualifierListOpt(DS);
5548  D.ExtendWithDeclSpec(DS);
5549 
5550  // Recurse to parse whatever is left.
5551  ParseDeclaratorInternal(D, DirectDeclParser);
5552 
5553  // Sema will have to catch (syntactically invalid) pointers into global
5554  // scope. It has to catch pointers into namespace scope anyway.
5556  SS, DS.getTypeQualifiers(), DS.getEndLoc()),
5557  std::move(DS.getAttributes()),
5558  /* Don't replace range end. */ SourceLocation());
5559  return;
5560  }
5561  }
5562 
5563  tok::TokenKind Kind = Tok.getKind();
5564 
5565  if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5566  DeclSpec DS(AttrFactory);
5567  ParseTypeQualifierListOpt(DS);
5568 
5569  D.AddTypeInfo(
5571  std::move(DS.getAttributes()), SourceLocation());
5572  }
5573 
5574  // Not a pointer, C++ reference, or block.
5575  if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5576  if (DirectDeclParser)
5577  (this->*DirectDeclParser)(D);
5578  return;
5579  }
5580 
5581  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5582  // '&&' -> rvalue reference
5583  SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
5584  D.SetRangeEnd(Loc);
5585 
5586  if (Kind == tok::star || Kind == tok::caret) {
5587  // Is a pointer.
5588  DeclSpec DS(AttrFactory);
5589 
5590  // GNU attributes are not allowed here in a new-type-id, but Declspec and
5591  // C++11 attributes are allowed.
5592  unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5594  ? AR_GNUAttributesParsed
5595  : AR_GNUAttributesParsedAndRejected);
5596  ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5597  D.ExtendWithDeclSpec(DS);
5598 
5599  // Recursively parse the declarator.
5600  ParseDeclaratorInternal(D, DirectDeclParser);
5601  if (Kind == tok::star)
5602  // Remember that we parsed a pointer type, and remember the type-quals.
5604  DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5607  std::move(DS.getAttributes()), SourceLocation());
5608  else
5609  // Remember that we parsed a Block type, and remember the type-quals.
5610  D.AddTypeInfo(
5612  std::move(DS.getAttributes()), SourceLocation());
5613  } else {
5614  // Is a reference
5615  DeclSpec DS(AttrFactory);
5616 
5617  // Complain about rvalue references in C++03, but then go on and build
5618  // the declarator.
5619  if (Kind == tok::ampamp)
5620  Diag(Loc, getLangOpts().CPlusPlus11 ?
5621  diag::warn_cxx98_compat_rvalue_reference :
5622  diag::ext_rvalue_reference);
5623 
5624  // GNU-style and C++11 attributes are allowed here, as is restrict.
5625  ParseTypeQualifierListOpt(DS);
5626  D.ExtendWithDeclSpec(DS);
5627 
5628  // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5629  // cv-qualifiers are introduced through the use of a typedef or of a
5630  // template type argument, in which case the cv-qualifiers are ignored.
5633  Diag(DS.getConstSpecLoc(),
5634  diag::err_invalid_reference_qualifier_application) << "const";
5636  Diag(DS.getVolatileSpecLoc(),
5637  diag::err_invalid_reference_qualifier_application) << "volatile";
5638  // 'restrict' is permitted as an extension.
5640  Diag(DS.getAtomicSpecLoc(),
5641  diag::err_invalid_reference_qualifier_application) << "_Atomic";
5642  }
5643 
5644  // Recursively parse the declarator.
5645  ParseDeclaratorInternal(D, DirectDeclParser);
5646 
5647  if (D.getNumTypeObjects() > 0) {
5648  // C++ [dcl.ref]p4: There shall be no references to references.
5649  DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5650  if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5651  if (const IdentifierInfo *II = D.getIdentifier())
5652  Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5653  << II;
5654  else
5655  Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5656  << "type name";
5657 
5658  // Once we've complained about the reference-to-reference, we
5659  // can go ahead and build the (technically ill-formed)
5660  // declarator: reference collapsing will take care of it.
5661  }
5662  }
5663 
5664  // Remember that we parsed a reference type.
5666  Kind == tok::amp),
5667  std::move(DS.getAttributes()), SourceLocation());
5668  }
5669 }
5670 
5671 // When correcting from misplaced brackets before the identifier, the location
5672 // is saved inside the declarator so that other diagnostic messages can use
5673 // them. This extracts and returns that location, or returns the provided
5674 // location if a stored location does not exist.
5676  SourceLocation Loc) {
5677  if (D.getName().StartLocation.isInvalid() &&
5678  D.getName().EndLocation.isValid())
5679  return D.getName().EndLocation;
5680 
5681  return Loc;
5682 }
5683 
5684 /// ParseDirectDeclarator
5685 /// direct-declarator: [C99 6.7.5]
5686 /// [C99] identifier
5687 /// '(' declarator ')'
5688 /// [GNU] '(' attributes declarator ')'
5689 /// [C90] direct-declarator '[' constant-expression[opt] ']'
5690 /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5691 /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5692 /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5693 /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
5694 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5695 /// attribute-specifier-seq[opt]
5696 /// direct-declarator '(' parameter-type-list ')'
5697 /// direct-declarator '(' identifier-list[opt] ')'
5698 /// [GNU] direct-declarator '(' parameter-forward-declarations
5699 /// parameter-type-list[opt] ')'
5700 /// [C++] direct-declarator '(' parameter-declaration-clause ')'
5701 /// cv-qualifier-seq[opt] exception-specification[opt]
5702 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5703 /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5704 /// ref-qualifier[opt] exception-specification[opt]
5705 /// [C++] declarator-id
5706 /// [C++11] declarator-id attribute-specifier-seq[opt]
5707 ///
5708 /// declarator-id: [C++ 8]
5709 /// '...'[opt] id-expression
5710 /// '::'[opt] nested-name-specifier[opt] type-name
5711 ///
5712 /// id-expression: [C++ 5.1]
5713 /// unqualified-id
5714 /// qualified-id
5715 ///
5716 /// unqualified-id: [C++ 5.1]
5717 /// identifier
5718 /// operator-function-id
5719 /// conversion-function-id
5720 /// '~' class-name
5721 /// template-id
5722 ///
5723 /// C++17 adds the following, which we also handle here:
5724 ///
5725 /// simple-declaration:
5726 /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5727 ///
5728 /// Note, any additional constructs added here may need corresponding changes
5729 /// in isConstructorDeclarator.
5730 void Parser::ParseDirectDeclarator(Declarator &D) {
5731  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5732 
5733  if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5734  // This might be a C++17 structured binding.
5735  if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5736  D.getCXXScopeSpec().isEmpty())
5737  return ParseDecompositionDeclarator(D);
5738 
5739  // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5740  // this context it is a bitfield. Also in range-based for statement colon
5741  // may delimit for-range-declaration.
5745  getLangOpts().CPlusPlus11));
5746 
5747  // ParseDeclaratorInternal might already have parsed the scope.
5748  if (D.getCXXScopeSpec().isEmpty()) {
5749  bool EnteringContext =
5752  ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5753  EnteringContext);
5754  }
5755 
5756  if (D.getCXXScopeSpec().isValid()) {
5757  if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5758  D.getCXXScopeSpec()))
5759  // Change the declaration context for name lookup, until this function
5760  // is exited (and the declarator has been parsed).
5761  DeclScopeObj.EnterDeclaratorScope();
5762  else if (getObjCDeclContext()) {
5763  // Ensure that we don't interpret the next token as an identifier when
5764  // dealing with declarations in an Objective-C container.
5765  D.SetIdentifier(nullptr, Tok.getLocation());
5766  D.setInvalidType(true);
5767  ConsumeToken();
5768  goto PastIdentifier;
5769  }
5770  }
5771 
5772  // C++0x [dcl.fct]p14:
5773  // There is a syntactic ambiguity when an ellipsis occurs at the end of a
5774  // parameter-declaration-clause without a preceding comma. In this case,
5775  // the ellipsis is parsed as part of the abstract-declarator if the type
5776  // of the parameter either names a template parameter pack that has not
5777  // been expanded or contains auto; otherwise, it is parsed as part of the
5778  // parameter-declaration-clause.
5779  if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5783  NextToken().is(tok::r_paren) &&
5784  !D.hasGroupingParens() &&
5785  !Actions.containsUnexpandedParameterPacks(D) &&
5786  D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5787  SourceLocation EllipsisLoc = ConsumeToken();
5788  if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5789  // The ellipsis was put in the wrong place. Recover, and explain to
5790  // the user what they should have done.
5791  ParseDeclarator(D);
5792  if (EllipsisLoc.isValid())
5793  DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5794  return;
5795  } else
5796  D.setEllipsisLoc(EllipsisLoc);
5797 
5798  // The ellipsis can't be followed by a parenthesized declarator. We
5799  // check for that in ParseParenDeclarator, after we have disambiguated
5800  // the l_paren token.
5801  }
5802 
5803  if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5804  tok::tilde)) {
5805  // We found something that indicates the start of an unqualified-id.
5806  // Parse that unqualified-id.
5807  bool AllowConstructorName;
5808  bool AllowDeductionGuide;
5809  if (D.getDeclSpec().hasTypeSpecifier()) {
5810  AllowConstructorName = false;
5811  AllowDeductionGuide = false;
5812  } else if (D.getCXXScopeSpec().isSet()) {
5813  AllowConstructorName =
5816  AllowDeductionGuide = false;
5817  } else {
5818  AllowConstructorName =
5820  AllowDeductionGuide =
5823  }
5824 
5825  bool HadScope = D.getCXXScopeSpec().isValid();
5827  /*EnteringContext=*/true,
5828  /*AllowDestructorName=*/true, AllowConstructorName,
5829  AllowDeductionGuide, nullptr, nullptr,
5830  D.getName()) ||
5831  // Once we're past the identifier, if the scope was bad, mark the
5832  // whole declarator bad.
5833  D.getCXXScopeSpec().isInvalid()) {
5834  D.SetIdentifier(nullptr, Tok.getLocation());
5835  D.setInvalidType(true);
5836  } else {
5837  // ParseUnqualifiedId might have parsed a scope specifier during error
5838  // recovery. If it did so, enter that scope.
5839  if (!HadScope && D.getCXXScopeSpec().isValid() &&
5840  Actions.ShouldEnterDeclaratorScope(getCurScope(),
5841  D.getCXXScopeSpec()))
5842  DeclScopeObj.EnterDeclaratorScope();
5843 
5844  // Parsed the unqualified-id; update range information and move along.
5845  if (D.getSourceRange().getBegin().isInvalid())
5848  }
5849  goto PastIdentifier;
5850  }
5851 
5852  if (D.getCXXScopeSpec().isNotEmpty()) {
5853  // We have a scope specifier but no following unqualified-id.
5854  Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5855  diag::err_expected_unqualified_id)
5856  << /*C++*/1;
5857  D.SetIdentifier(nullptr, Tok.getLocation());
5858  goto PastIdentifier;
5859  }
5860  } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5861  assert(!getLangOpts().CPlusPlus &&
5862  "There's a C++-specific check for tok::identifier above");
5863  assert(Tok.getIdentifierInfo() && "Not an identifier?");
5865  D.SetRangeEnd(Tok.getLocation());
5866  ConsumeToken();
5867  goto PastIdentifier;
5868  } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5869  // We're not allowed an identifier here, but we got one. Try to figure out
5870  // if the user was trying to attach a name to the type, or whether the name
5871  // is some unrelated trailing syntax.
5872  bool DiagnoseIdentifier = false;
5873  if (D.hasGroupingParens())
5874  // An identifier within parens is unlikely to be intended to be anything
5875  // other than a name being "declared".
5876  DiagnoseIdentifier = true;
5878  // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5879  DiagnoseIdentifier =
5880  NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5883  // The most likely error is that the ';' was forgotten.
5884  DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5887  !isCXX11VirtSpecifier(Tok))
5888  DiagnoseIdentifier = NextToken().isOneOf(
5889  tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5890  if (DiagnoseIdentifier) {
5891  Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5893  D.SetIdentifier(nullptr, Tok.getLocation());
5894  ConsumeToken();
5895  goto PastIdentifier;
5896  }
5897  }
5898 
5899  if (Tok.is(tok::l_paren)) {
5900  // If this might be an abstract-declarator followed by a direct-initializer,
5901  // check whether this is a valid declarator chunk. If it can't be, assume
5902  // that it's an initializer instead.
5904  RevertingTentativeParsingAction PA(*this);
5905  if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5906  TPResult::False) {
5907  D.SetIdentifier(nullptr, Tok.getLocation());
5908  goto PastIdentifier;
5909  }
5910  }
5911 
5912  // direct-declarator: '(' declarator ')'
5913  // direct-declarator: '(' attributes declarator ')'
5914  // Example: 'char (*X)' or 'int (*XX)(void)'
5915  ParseParenDeclarator(D);
5916 
5917  // If the declarator was parenthesized, we entered the declarator
5918  // scope when parsing the parenthesized declarator, then exited
5919  // the scope already. Re-enter the scope, if we need to.
5920  if (D.getCXXScopeSpec().isSet()) {
5921  // If there was an error parsing parenthesized declarator, declarator
5922  // scope may have been entered before. Don't do it again.
5923  if (!D.isInvalidType() &&
5924  Actions.ShouldEnterDeclaratorScope(getCurScope(),
5925  D.getCXXScopeSpec()))
5926  // Change the declaration context for name lookup, until this function
5927  // is exited (and the declarator has been parsed).
5928  DeclScopeObj.EnterDeclaratorScope();
5929  }
5930  } else if (D.mayOmitIdentifier()) {
5931  // This could be something simple like "int" (in which case the declarator
5932  // portion is empty), if an abstract-declarator is allowed.
5933  D.SetIdentifier(nullptr, Tok.getLocation());
5934 
5935  // The grammar for abstract-pack-declarator does not allow grouping parens.
5936  // FIXME: Revisit this once core issue 1488 is resolved.
5937  if (D.hasEllipsis() && D.hasGroupingParens())
5938  Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5939  diag::ext_abstract_pack_declarator_parens);
5940  } else {
5941  if (Tok.getKind() == tok::annot_pragma_parser_crash)
5942  LLVM_BUILTIN_TRAP;
5943  if (Tok.is(tok::l_square))
5944  return ParseMisplacedBracketDeclarator(D);
5946  // Objective-C++: Detect C++ keywords and try to prevent further errors by
5947  // treating these keyword as valid member names.
5948  if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
5949  Tok.getIdentifierInfo() &&
5952  diag::err_expected_member_name_or_semi_objcxx_keyword)
5953  << Tok.getIdentifierInfo()
5954  << (D.getDeclSpec().isEmpty() ? SourceRange()
5955  : D.getDeclSpec().getSourceRange());
5957  D.SetRangeEnd(Tok.getLocation());
5958  ConsumeToken();
5959  goto PastIdentifier;
5960  }
5962  diag::err_expected_member_name_or_semi)
5963  << (D.