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