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