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