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