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