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