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