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