ParseDecl.cpp revision bb85f8edca8103aa10e4b2f4a6fcc3a251b0ea03
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/OpenCL.h"
17#include "clang/Sema/Scope.h"
18#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/PrettyDeclStackTrace.h"
20#include "RAIIObjectsForParser.h"
21#include "llvm/ADT/SmallSet.h"
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// C99 6.7: Declarations.
26//===----------------------------------------------------------------------===//
27
28/// ParseTypeName
29///       type-name: [C99 6.7.6]
30///         specifier-qualifier-list abstract-declarator[opt]
31///
32/// Called type-id in C++.
33TypeResult Parser::ParseTypeName(SourceRange *Range,
34                                 Declarator::TheContext Context) {
35  // Parse the common declaration-specifiers piece.
36  DeclSpec DS(AttrFactory);
37  ParseSpecifierQualifierList(DS);
38
39  // Parse the abstract-declarator, if present.
40  Declarator DeclaratorInfo(DS, Context);
41  ParseDeclarator(DeclaratorInfo);
42  if (Range)
43    *Range = DeclaratorInfo.getSourceRange();
44
45  if (DeclaratorInfo.isInvalidType())
46    return true;
47
48  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
49}
50
51/// ParseGNUAttributes - Parse a non-empty attributes list.
52///
53/// [GNU] attributes:
54///         attribute
55///         attributes attribute
56///
57/// [GNU]  attribute:
58///          '__attribute__' '(' '(' attribute-list ')' ')'
59///
60/// [GNU]  attribute-list:
61///          attrib
62///          attribute_list ',' attrib
63///
64/// [GNU]  attrib:
65///          empty
66///          attrib-name
67///          attrib-name '(' identifier ')'
68///          attrib-name '(' identifier ',' nonempty-expr-list ')'
69///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
70///
71/// [GNU]  attrib-name:
72///          identifier
73///          typespec
74///          typequal
75///          storageclass
76///
77/// FIXME: The GCC grammar/code for this construct implies we need two
78/// token lookahead. Comment from gcc: "If they start with an identifier
79/// which is followed by a comma or close parenthesis, then the arguments
80/// start with that identifier; otherwise they are an expression list."
81///
82/// At the moment, I am not doing 2 token lookahead. I am also unaware of
83/// any attributes that don't work (based on my limited testing). Most
84/// attributes are very simple in practice. Until we find a bug, I don't see
85/// a pressing need to implement the 2 token lookahead.
86
87void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
88                                SourceLocation *endLoc) {
89  assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
90
91  while (Tok.is(tok::kw___attribute)) {
92    ConsumeToken();
93    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
94                         "attribute")) {
95      SkipUntil(tok::r_paren, true); // skip until ) or ;
96      return;
97    }
98    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
99      SkipUntil(tok::r_paren, true); // skip until ) or ;
100      return;
101    }
102    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
103    while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
104           Tok.is(tok::comma)) {
105
106      if (Tok.is(tok::comma)) {
107        // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
108        ConsumeToken();
109        continue;
110      }
111      // we have an identifier or declaration specifier (const, int, etc.)
112      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
113      SourceLocation AttrNameLoc = ConsumeToken();
114
115      // Availability attributes have their own grammar.
116      if (AttrName->isStr("availability"))
117        ParseAvailabilityAttribute(*AttrName, AttrNameLoc, attrs, endLoc);
118      // check if we have a "parameterized" attribute
119      else if (Tok.is(tok::l_paren)) {
120        ConsumeParen(); // ignore the left paren loc for now
121
122        if (Tok.is(tok::identifier)) {
123          IdentifierInfo *ParmName = Tok.getIdentifierInfo();
124          SourceLocation ParmLoc = ConsumeToken();
125
126          if (Tok.is(tok::r_paren)) {
127            // __attribute__(( mode(byte) ))
128            ConsumeParen(); // ignore the right paren loc for now
129            attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
130                         ParmName, ParmLoc, 0, 0);
131          } else if (Tok.is(tok::comma)) {
132            ConsumeToken();
133            // __attribute__(( format(printf, 1, 2) ))
134            ExprVector ArgExprs(Actions);
135            bool ArgExprsOk = true;
136
137            // now parse the non-empty comma separated list of expressions
138            while (1) {
139              ExprResult ArgExpr(ParseAssignmentExpression());
140              if (ArgExpr.isInvalid()) {
141                ArgExprsOk = false;
142                SkipUntil(tok::r_paren);
143                break;
144              } else {
145                ArgExprs.push_back(ArgExpr.release());
146              }
147              if (Tok.isNot(tok::comma))
148                break;
149              ConsumeToken(); // Eat the comma, move to the next argument
150            }
151            if (ArgExprsOk && Tok.is(tok::r_paren)) {
152              ConsumeParen(); // ignore the right paren loc for now
153              attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
154                           ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size());
155            }
156          }
157        } else { // not an identifier
158          switch (Tok.getKind()) {
159          case tok::r_paren:
160          // parse a possibly empty comma separated list of expressions
161            // __attribute__(( nonnull() ))
162            ConsumeParen(); // ignore the right paren loc for now
163            attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
164                         0, SourceLocation(), 0, 0);
165            break;
166          case tok::kw_char:
167          case tok::kw_wchar_t:
168          case tok::kw_char16_t:
169          case tok::kw_char32_t:
170          case tok::kw_bool:
171          case tok::kw_short:
172          case tok::kw_int:
173          case tok::kw_long:
174          case tok::kw___int64:
175          case tok::kw_signed:
176          case tok::kw_unsigned:
177          case tok::kw_float:
178          case tok::kw_double:
179          case tok::kw_void:
180          case tok::kw_typeof: {
181            AttributeList *attr
182              = attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
183                             0, SourceLocation(), 0, 0);
184            if (attr->getKind() == AttributeList::AT_IBOutletCollection)
185              Diag(Tok, diag::err_iboutletcollection_builtintype);
186            // If it's a builtin type name, eat it and expect a rparen
187            // __attribute__(( vec_type_hint(char) ))
188            ConsumeToken();
189            if (Tok.is(tok::r_paren))
190              ConsumeParen();
191            break;
192          }
193          default:
194            // __attribute__(( aligned(16) ))
195            ExprVector ArgExprs(Actions);
196            bool ArgExprsOk = true;
197
198            // now parse the list of expressions
199            while (1) {
200              ExprResult ArgExpr(ParseAssignmentExpression());
201              if (ArgExpr.isInvalid()) {
202                ArgExprsOk = false;
203                SkipUntil(tok::r_paren);
204                break;
205              } else {
206                ArgExprs.push_back(ArgExpr.release());
207              }
208              if (Tok.isNot(tok::comma))
209                break;
210              ConsumeToken(); // Eat the comma, move to the next argument
211            }
212            // Match the ')'.
213            if (ArgExprsOk && Tok.is(tok::r_paren)) {
214              ConsumeParen(); // ignore the right paren loc for now
215              attrs.addNew(AttrName, AttrNameLoc, 0,
216                           AttrNameLoc, 0, SourceLocation(),
217                           ArgExprs.take(), ArgExprs.size());
218            }
219            break;
220          }
221        }
222      } else {
223        attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
224                     0, SourceLocation(), 0, 0);
225      }
226    }
227    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
228      SkipUntil(tok::r_paren, false);
229    SourceLocation Loc = Tok.getLocation();
230    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
231      SkipUntil(tok::r_paren, false);
232    }
233    if (endLoc)
234      *endLoc = Loc;
235  }
236}
237
238/// ParseMicrosoftDeclSpec - Parse an __declspec construct
239///
240/// [MS] decl-specifier:
241///             __declspec ( extended-decl-modifier-seq )
242///
243/// [MS] extended-decl-modifier-seq:
244///             extended-decl-modifier[opt]
245///             extended-decl-modifier extended-decl-modifier-seq
246
247void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &attrs) {
248  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
249
250  ConsumeToken();
251  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
252                       "declspec")) {
253    SkipUntil(tok::r_paren, true); // skip until ) or ;
254    return;
255  }
256  while (Tok.getIdentifierInfo()) {
257    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
258    SourceLocation AttrNameLoc = ConsumeToken();
259    if (Tok.is(tok::l_paren)) {
260      ConsumeParen();
261      // FIXME: This doesn't parse __declspec(property(get=get_func_name))
262      // correctly.
263      ExprResult ArgExpr(ParseAssignmentExpression());
264      if (!ArgExpr.isInvalid()) {
265        Expr *ExprList = ArgExpr.take();
266        attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
267                     SourceLocation(), &ExprList, 1, true);
268      }
269      if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
270        SkipUntil(tok::r_paren, false);
271    } else {
272      attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
273                   0, SourceLocation(), 0, 0, true);
274    }
275  }
276  if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
277    SkipUntil(tok::r_paren, false);
278  return;
279}
280
281void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
282  // Treat these like attributes
283  // FIXME: Allow Sema to distinguish between these and real attributes!
284  while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
285         Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl)   ||
286         Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64)) {
287    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
288    SourceLocation AttrNameLoc = ConsumeToken();
289    if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64))
290      // FIXME: Support these properly!
291      continue;
292    attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
293                 SourceLocation(), 0, 0, true);
294  }
295}
296
297void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
298  // Treat these like attributes
299  while (Tok.is(tok::kw___pascal)) {
300    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
301    SourceLocation AttrNameLoc = ConsumeToken();
302    attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
303                 SourceLocation(), 0, 0, true);
304  }
305}
306
307void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
308  // Treat these like attributes
309  while (Tok.is(tok::kw___kernel)) {
310    SourceLocation AttrNameLoc = ConsumeToken();
311    attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"),
312                 AttrNameLoc, 0, AttrNameLoc, 0,
313                 SourceLocation(), 0, 0, false);
314  }
315}
316
317void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
318  SourceLocation Loc = Tok.getLocation();
319  switch(Tok.getKind()) {
320    // OpenCL qualifiers:
321    case tok::kw___private:
322    case tok::kw_private:
323      DS.getAttributes().addNewInteger(
324          Actions.getASTContext(),
325          PP.getIdentifierInfo("address_space"), Loc, 0);
326      break;
327
328    case tok::kw___global:
329      DS.getAttributes().addNewInteger(
330          Actions.getASTContext(),
331          PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
332      break;
333
334    case tok::kw___local:
335      DS.getAttributes().addNewInteger(
336          Actions.getASTContext(),
337          PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
338      break;
339
340    case tok::kw___constant:
341      DS.getAttributes().addNewInteger(
342          Actions.getASTContext(),
343          PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
344      break;
345
346    case tok::kw___read_only:
347      DS.getAttributes().addNewInteger(
348          Actions.getASTContext(),
349          PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
350      break;
351
352    case tok::kw___write_only:
353      DS.getAttributes().addNewInteger(
354          Actions.getASTContext(),
355          PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
356      break;
357
358    case tok::kw___read_write:
359      DS.getAttributes().addNewInteger(
360          Actions.getASTContext(),
361          PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
362      break;
363    default: break;
364  }
365}
366
367/// \brief Parse a version number.
368///
369/// version:
370///   simple-integer
371///   simple-integer ',' simple-integer
372///   simple-integer ',' simple-integer ',' simple-integer
373VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
374  Range = Tok.getLocation();
375
376  if (!Tok.is(tok::numeric_constant)) {
377    Diag(Tok, diag::err_expected_version);
378    SkipUntil(tok::comma, tok::r_paren, true, true, true);
379    return VersionTuple();
380  }
381
382  // Parse the major (and possibly minor and subminor) versions, which
383  // are stored in the numeric constant. We utilize a quirk of the
384  // lexer, which is that it handles something like 1.2.3 as a single
385  // numeric constant, rather than two separate tokens.
386  llvm::SmallString<512> Buffer;
387  Buffer.resize(Tok.getLength()+1);
388  const char *ThisTokBegin = &Buffer[0];
389
390  // Get the spelling of the token, which eliminates trigraphs, etc.
391  bool Invalid = false;
392  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
393  if (Invalid)
394    return VersionTuple();
395
396  // Parse the major version.
397  unsigned AfterMajor = 0;
398  unsigned Major = 0;
399  while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) {
400    Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
401    ++AfterMajor;
402  }
403
404  if (AfterMajor == 0) {
405    Diag(Tok, diag::err_expected_version);
406    SkipUntil(tok::comma, tok::r_paren, true, true, true);
407    return VersionTuple();
408  }
409
410  if (AfterMajor == ActualLength) {
411    ConsumeToken();
412
413    // We only had a single version component.
414    if (Major == 0) {
415      Diag(Tok, diag::err_zero_version);
416      return VersionTuple();
417    }
418
419    return VersionTuple(Major);
420  }
421
422  if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
423    Diag(Tok, diag::err_expected_version);
424    SkipUntil(tok::comma, tok::r_paren, true, true, true);
425    return VersionTuple();
426  }
427
428  // Parse the minor version.
429  unsigned AfterMinor = AfterMajor + 1;
430  unsigned Minor = 0;
431  while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) {
432    Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
433    ++AfterMinor;
434  }
435
436  if (AfterMinor == ActualLength) {
437    ConsumeToken();
438
439    // We had major.minor.
440    if (Major == 0 && Minor == 0) {
441      Diag(Tok, diag::err_zero_version);
442      return VersionTuple();
443    }
444
445    return VersionTuple(Major, Minor);
446  }
447
448  // If what follows is not a '.', we have a problem.
449  if (ThisTokBegin[AfterMinor] != '.') {
450    Diag(Tok, diag::err_expected_version);
451    SkipUntil(tok::comma, tok::r_paren, true, true, true);
452    return VersionTuple();
453  }
454
455  // Parse the subminor version.
456  unsigned AfterSubminor = AfterMinor + 1;
457  unsigned Subminor = 0;
458  while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) {
459    Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
460    ++AfterSubminor;
461  }
462
463  if (AfterSubminor != ActualLength) {
464    Diag(Tok, diag::err_expected_version);
465    SkipUntil(tok::comma, tok::r_paren, true, true, true);
466    return VersionTuple();
467  }
468  ConsumeToken();
469  return VersionTuple(Major, Minor, Subminor);
470}
471
472/// \brief Parse the contents of the "availability" attribute.
473///
474/// availability-attribute:
475///   'availability' '(' platform ',' version-arg-list ')'
476///
477/// platform:
478///   identifier
479///
480/// version-arg-list:
481///   version-arg
482///   version-arg ',' version-arg-list
483///
484/// version-arg:
485///   'introduced' '=' version
486///   'deprecated' '=' version
487///   'removed' = version
488///   'unavailable'
489void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
490                                        SourceLocation AvailabilityLoc,
491                                        ParsedAttributes &attrs,
492                                        SourceLocation *endLoc) {
493  SourceLocation PlatformLoc;
494  IdentifierInfo *Platform = 0;
495
496  enum { Introduced, Deprecated, Obsoleted, Unknown };
497  AvailabilityChange Changes[Unknown];
498
499  // Opening '('.
500  SourceLocation LParenLoc;
501  if (!Tok.is(tok::l_paren)) {
502    Diag(Tok, diag::err_expected_lparen);
503    return;
504  }
505  LParenLoc = ConsumeParen();
506
507  // Parse the platform name,
508  if (Tok.isNot(tok::identifier)) {
509    Diag(Tok, diag::err_availability_expected_platform);
510    SkipUntil(tok::r_paren);
511    return;
512  }
513  Platform = Tok.getIdentifierInfo();
514  PlatformLoc = ConsumeToken();
515
516  // Parse the ',' following the platform name.
517  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
518    return;
519
520  // If we haven't grabbed the pointers for the identifiers
521  // "introduced", "deprecated", and "obsoleted", do so now.
522  if (!Ident_introduced) {
523    Ident_introduced = PP.getIdentifierInfo("introduced");
524    Ident_deprecated = PP.getIdentifierInfo("deprecated");
525    Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
526    Ident_unavailable = PP.getIdentifierInfo("unavailable");
527  }
528
529  // Parse the set of introductions/deprecations/removals.
530  SourceLocation UnavailableLoc;
531  do {
532    if (Tok.isNot(tok::identifier)) {
533      Diag(Tok, diag::err_availability_expected_change);
534      SkipUntil(tok::r_paren);
535      return;
536    }
537    IdentifierInfo *Keyword = Tok.getIdentifierInfo();
538    SourceLocation KeywordLoc = ConsumeToken();
539
540    if (Keyword == Ident_unavailable) {
541      if (UnavailableLoc.isValid()) {
542        Diag(KeywordLoc, diag::err_availability_redundant)
543          << Keyword << SourceRange(UnavailableLoc);
544      }
545      UnavailableLoc = KeywordLoc;
546
547      if (Tok.isNot(tok::comma))
548        break;
549
550      ConsumeToken();
551      continue;
552    }
553
554    if (Tok.isNot(tok::equal)) {
555      Diag(Tok, diag::err_expected_equal_after)
556        << Keyword;
557      SkipUntil(tok::r_paren);
558      return;
559    }
560    ConsumeToken();
561
562    SourceRange VersionRange;
563    VersionTuple Version = ParseVersionTuple(VersionRange);
564
565    if (Version.empty()) {
566      SkipUntil(tok::r_paren);
567      return;
568    }
569
570    unsigned Index;
571    if (Keyword == Ident_introduced)
572      Index = Introduced;
573    else if (Keyword == Ident_deprecated)
574      Index = Deprecated;
575    else if (Keyword == Ident_obsoleted)
576      Index = Obsoleted;
577    else
578      Index = Unknown;
579
580    if (Index < Unknown) {
581      if (!Changes[Index].KeywordLoc.isInvalid()) {
582        Diag(KeywordLoc, diag::err_availability_redundant)
583          << Keyword
584          << SourceRange(Changes[Index].KeywordLoc,
585                         Changes[Index].VersionRange.getEnd());
586      }
587
588      Changes[Index].KeywordLoc = KeywordLoc;
589      Changes[Index].Version = Version;
590      Changes[Index].VersionRange = VersionRange;
591    } else {
592      Diag(KeywordLoc, diag::err_availability_unknown_change)
593        << Keyword << VersionRange;
594    }
595
596    if (Tok.isNot(tok::comma))
597      break;
598
599    ConsumeToken();
600  } while (true);
601
602  // Closing ')'.
603  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
604  if (RParenLoc.isInvalid())
605    return;
606
607  if (endLoc)
608    *endLoc = RParenLoc;
609
610  // The 'unavailable' availability cannot be combined with any other
611  // availability changes. Make sure that hasn't happened.
612  if (UnavailableLoc.isValid()) {
613    bool Complained = false;
614    for (unsigned Index = Introduced; Index != Unknown; ++Index) {
615      if (Changes[Index].KeywordLoc.isValid()) {
616        if (!Complained) {
617          Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
618            << SourceRange(Changes[Index].KeywordLoc,
619                           Changes[Index].VersionRange.getEnd());
620          Complained = true;
621        }
622
623        // Clear out the availability.
624        Changes[Index] = AvailabilityChange();
625      }
626    }
627  }
628
629  // Record this attribute
630  attrs.addNew(&Availability, AvailabilityLoc,
631               0, SourceLocation(),
632               Platform, PlatformLoc,
633               Changes[Introduced],
634               Changes[Deprecated],
635               Changes[Obsoleted],
636               UnavailableLoc, false, false);
637}
638
639void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
640  Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
641    << attrs.Range;
642}
643
644/// ParseDeclaration - Parse a full 'declaration', which consists of
645/// declaration-specifiers, some number of declarators, and a semicolon.
646/// 'Context' should be a Declarator::TheContext value.  This returns the
647/// location of the semicolon in DeclEnd.
648///
649///       declaration: [C99 6.7]
650///         block-declaration ->
651///           simple-declaration
652///           others                   [FIXME]
653/// [C++]   template-declaration
654/// [C++]   namespace-definition
655/// [C++]   using-directive
656/// [C++]   using-declaration
657/// [C++0x/C1X] static_assert-declaration
658///         others... [FIXME]
659///
660Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
661                                                unsigned Context,
662                                                SourceLocation &DeclEnd,
663                                          ParsedAttributesWithRange &attrs) {
664  ParenBraceBracketBalancer BalancerRAIIObj(*this);
665
666  Decl *SingleDecl = 0;
667  switch (Tok.getKind()) {
668  case tok::kw_template:
669  case tok::kw_export:
670    ProhibitAttributes(attrs);
671    SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
672    break;
673  case tok::kw_inline:
674    // Could be the start of an inline namespace. Allowed as an ext in C++03.
675    if (getLang().CPlusPlus && NextToken().is(tok::kw_namespace)) {
676      ProhibitAttributes(attrs);
677      SourceLocation InlineLoc = ConsumeToken();
678      SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
679      break;
680    }
681    return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
682                                  true);
683  case tok::kw_namespace:
684    ProhibitAttributes(attrs);
685    SingleDecl = ParseNamespace(Context, DeclEnd);
686    break;
687  case tok::kw_using:
688    SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
689                                                  DeclEnd, attrs);
690    break;
691  case tok::kw_static_assert:
692  case tok::kw__Static_assert:
693    ProhibitAttributes(attrs);
694    SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
695    break;
696  default:
697    return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
698  }
699
700  // This routine returns a DeclGroup, if the thing we parsed only contains a
701  // single decl, convert it now.
702  return Actions.ConvertDeclToDeclGroup(SingleDecl);
703}
704
705///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
706///         declaration-specifiers init-declarator-list[opt] ';'
707///[C90/C++]init-declarator-list ';'                             [TODO]
708/// [OMP]   threadprivate-directive                              [TODO]
709///
710///       for-range-declaration: [C++0x 6.5p1: stmt.ranged]
711///         attribute-specifier-seq[opt] type-specifier-seq declarator
712///
713/// If RequireSemi is false, this does not check for a ';' at the end of the
714/// declaration.  If it is true, it checks for and eats it.
715///
716/// If FRI is non-null, we might be parsing a for-range-declaration instead
717/// of a simple-declaration. If we find that we are, we also parse the
718/// for-range-initializer, and place it here.
719Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts,
720                                                      unsigned Context,
721                                                      SourceLocation &DeclEnd,
722                                                      ParsedAttributes &attrs,
723                                                      bool RequireSemi,
724                                                      ForRangeInit *FRI) {
725  // Parse the common declaration-specifiers piece.
726  ParsingDeclSpec DS(*this);
727  DS.takeAttributesFrom(attrs);
728
729  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
730                             getDeclSpecContextFromDeclaratorContext(Context));
731  StmtResult R = Actions.ActOnVlaStmt(DS);
732  if (R.isUsable())
733    Stmts.push_back(R.release());
734
735  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
736  // declaration-specifiers init-declarator-list[opt] ';'
737  if (Tok.is(tok::semi)) {
738    if (RequireSemi) ConsumeToken();
739    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
740                                                       DS);
741    DS.complete(TheDecl);
742    return Actions.ConvertDeclToDeclGroup(TheDecl);
743  }
744
745  return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
746}
747
748/// ParseDeclGroup - Having concluded that this is either a function
749/// definition or a group of object declarations, actually parse the
750/// result.
751Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
752                                              unsigned Context,
753                                              bool AllowFunctionDefinitions,
754                                              SourceLocation *DeclEnd,
755                                              ForRangeInit *FRI) {
756  // Parse the first declarator.
757  ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
758  ParseDeclarator(D);
759
760  // Bail out if the first declarator didn't seem well-formed.
761  if (!D.hasName() && !D.mayOmitIdentifier()) {
762    // Skip until ; or }.
763    SkipUntil(tok::r_brace, true, true);
764    if (Tok.is(tok::semi))
765      ConsumeToken();
766    return DeclGroupPtrTy();
767  }
768
769  // Check to see if we have a function *definition* which must have a body.
770  if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
771      // Look at the next token to make sure that this isn't a function
772      // declaration.  We have to check this because __attribute__ might be the
773      // start of a function definition in GCC-extended K&R C.
774      !isDeclarationAfterDeclarator()) {
775
776    if (isStartOfFunctionDefinition(D)) {
777      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
778        Diag(Tok, diag::err_function_declared_typedef);
779
780        // Recover by treating the 'typedef' as spurious.
781        DS.ClearStorageClassSpecs();
782      }
783
784      Decl *TheDecl = ParseFunctionDefinition(D);
785      return Actions.ConvertDeclToDeclGroup(TheDecl);
786    }
787
788    if (isDeclarationSpecifier()) {
789      // If there is an invalid declaration specifier right after the function
790      // prototype, then we must be in a missing semicolon case where this isn't
791      // actually a body.  Just fall through into the code that handles it as a
792      // prototype, and let the top-level code handle the erroneous declspec
793      // where it would otherwise expect a comma or semicolon.
794    } else {
795      Diag(Tok, diag::err_expected_fn_body);
796      SkipUntil(tok::semi);
797      return DeclGroupPtrTy();
798    }
799  }
800
801  if (ParseAttributesAfterDeclarator(D))
802    return DeclGroupPtrTy();
803
804  // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
805  // must parse and analyze the for-range-initializer before the declaration is
806  // analyzed.
807  if (FRI && Tok.is(tok::colon)) {
808    FRI->ColonLoc = ConsumeToken();
809    // FIXME: handle braced-init-list here.
810    FRI->RangeExpr = ParseExpression();
811    Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
812    Actions.ActOnCXXForRangeDecl(ThisDecl);
813    Actions.FinalizeDeclaration(ThisDecl);
814    return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1);
815  }
816
817  llvm::SmallVector<Decl *, 8> DeclsInGroup;
818  Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
819  D.complete(FirstDecl);
820  if (FirstDecl)
821    DeclsInGroup.push_back(FirstDecl);
822
823  // If we don't have a comma, it is either the end of the list (a ';') or an
824  // error, bail out.
825  while (Tok.is(tok::comma)) {
826    // Consume the comma.
827    ConsumeToken();
828
829    // Parse the next declarator.
830    D.clear();
831
832    // Accept attributes in an init-declarator.  In the first declarator in a
833    // declaration, these would be part of the declspec.  In subsequent
834    // declarators, they become part of the declarator itself, so that they
835    // don't apply to declarators after *this* one.  Examples:
836    //    short __attribute__((common)) var;    -> declspec
837    //    short var __attribute__((common));    -> declarator
838    //    short x, __attribute__((common)) var;    -> declarator
839    MaybeParseGNUAttributes(D);
840
841    ParseDeclarator(D);
842
843    Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
844    D.complete(ThisDecl);
845    if (ThisDecl)
846      DeclsInGroup.push_back(ThisDecl);
847  }
848
849  if (DeclEnd)
850    *DeclEnd = Tok.getLocation();
851
852  if (Context != Declarator::ForContext &&
853      ExpectAndConsume(tok::semi,
854                       Context == Declarator::FileContext
855                         ? diag::err_invalid_token_after_toplevel_declarator
856                         : diag::err_expected_semi_declaration)) {
857    // Okay, there was no semicolon and one was expected.  If we see a
858    // declaration specifier, just assume it was missing and continue parsing.
859    // Otherwise things are very confused and we skip to recover.
860    if (!isDeclarationSpecifier()) {
861      SkipUntil(tok::r_brace, true, true);
862      if (Tok.is(tok::semi))
863        ConsumeToken();
864    }
865  }
866
867  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
868                                         DeclsInGroup.data(),
869                                         DeclsInGroup.size());
870}
871
872/// Parse an optional simple-asm-expr and attributes, and attach them to a
873/// declarator. Returns true on an error.
874bool Parser::ParseAttributesAfterDeclarator(Declarator &D) {
875  // If a simple-asm-expr is present, parse it.
876  if (Tok.is(tok::kw_asm)) {
877    SourceLocation Loc;
878    ExprResult AsmLabel(ParseSimpleAsm(&Loc));
879    if (AsmLabel.isInvalid()) {
880      SkipUntil(tok::semi, true, true);
881      return true;
882    }
883
884    D.setAsmLabel(AsmLabel.release());
885    D.SetRangeEnd(Loc);
886  }
887
888  MaybeParseGNUAttributes(D);
889  return false;
890}
891
892/// \brief Parse 'declaration' after parsing 'declaration-specifiers
893/// declarator'. This method parses the remainder of the declaration
894/// (including any attributes or initializer, among other things) and
895/// finalizes the declaration.
896///
897///       init-declarator: [C99 6.7]
898///         declarator
899///         declarator '=' initializer
900/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
901/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
902/// [C++]   declarator initializer[opt]
903///
904/// [C++] initializer:
905/// [C++]   '=' initializer-clause
906/// [C++]   '(' expression-list ')'
907/// [C++0x] '=' 'default'                                                [TODO]
908/// [C++0x] '=' 'delete'
909///
910/// According to the standard grammar, =default and =delete are function
911/// definitions, but that definitely doesn't fit with the parser here.
912///
913Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
914                                     const ParsedTemplateInfo &TemplateInfo) {
915  if (ParseAttributesAfterDeclarator(D))
916    return 0;
917
918  return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
919}
920
921Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
922                                     const ParsedTemplateInfo &TemplateInfo) {
923  // Inform the current actions module that we just parsed this declarator.
924  Decl *ThisDecl = 0;
925  switch (TemplateInfo.Kind) {
926  case ParsedTemplateInfo::NonTemplate:
927    ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
928    break;
929
930  case ParsedTemplateInfo::Template:
931  case ParsedTemplateInfo::ExplicitSpecialization:
932    ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
933                             MultiTemplateParamsArg(Actions,
934                                          TemplateInfo.TemplateParams->data(),
935                                          TemplateInfo.TemplateParams->size()),
936                                               D);
937    break;
938
939  case ParsedTemplateInfo::ExplicitInstantiation: {
940    DeclResult ThisRes
941      = Actions.ActOnExplicitInstantiation(getCurScope(),
942                                           TemplateInfo.ExternLoc,
943                                           TemplateInfo.TemplateLoc,
944                                           D);
945    if (ThisRes.isInvalid()) {
946      SkipUntil(tok::semi, true, true);
947      return 0;
948    }
949
950    ThisDecl = ThisRes.get();
951    break;
952    }
953  }
954
955  bool TypeContainsAuto =
956    D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
957
958  // Parse declarator '=' initializer.
959  if (isTokenEqualOrMistypedEqualEqual(
960                               diag::err_invalid_equalequal_after_declarator)) {
961    ConsumeToken();
962    if (Tok.is(tok::kw_delete)) {
963      SourceLocation DelLoc = ConsumeToken();
964
965      if (!getLang().CPlusPlus0x)
966        Diag(DelLoc, diag::warn_deleted_function_accepted_as_extension);
967
968      Actions.SetDeclDeleted(ThisDecl, DelLoc);
969    } else if (Tok.is(tok::kw_default)) {
970      Diag(ConsumeToken(), diag::err_default_special_members);
971    } else {
972      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
973        EnterScope(0);
974        Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
975      }
976
977      if (Tok.is(tok::code_completion)) {
978        Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
979        ConsumeCodeCompletionToken();
980        SkipUntil(tok::comma, true, true);
981        return ThisDecl;
982      }
983
984      ExprResult Init(ParseInitializer());
985
986      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
987        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
988        ExitScope();
989      }
990
991      if (Init.isInvalid()) {
992        SkipUntil(tok::comma, true, true);
993        Actions.ActOnInitializerError(ThisDecl);
994      } else
995        Actions.AddInitializerToDecl(ThisDecl, Init.take(),
996                                     /*DirectInit=*/false, TypeContainsAuto);
997    }
998  } else if (Tok.is(tok::l_paren)) {
999    // Parse C++ direct initializer: '(' expression-list ')'
1000    SourceLocation LParenLoc = ConsumeParen();
1001    ExprVector Exprs(Actions);
1002    CommaLocsTy CommaLocs;
1003
1004    if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1005      EnterScope(0);
1006      Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1007    }
1008
1009    if (ParseExpressionList(Exprs, CommaLocs)) {
1010      SkipUntil(tok::r_paren);
1011
1012      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1013        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1014        ExitScope();
1015      }
1016    } else {
1017      // Match the ')'.
1018      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1019
1020      assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1021             "Unexpected number of commas!");
1022
1023      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1024        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1025        ExitScope();
1026      }
1027
1028      Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc,
1029                                            move_arg(Exprs),
1030                                            RParenLoc,
1031                                            TypeContainsAuto);
1032    }
1033  } else {
1034    Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1035  }
1036
1037  Actions.FinalizeDeclaration(ThisDecl);
1038
1039  return ThisDecl;
1040}
1041
1042/// ParseSpecifierQualifierList
1043///        specifier-qualifier-list:
1044///          type-specifier specifier-qualifier-list[opt]
1045///          type-qualifier specifier-qualifier-list[opt]
1046/// [GNU]    attributes     specifier-qualifier-list[opt]
1047///
1048void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
1049  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
1050  /// parse declaration-specifiers and complain about extra stuff.
1051  ParseDeclarationSpecifiers(DS);
1052
1053  // Validate declspec for type-name.
1054  unsigned Specs = DS.getParsedSpecifiers();
1055  if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1056      !DS.hasAttributes())
1057    Diag(Tok, diag::err_typename_requires_specqual);
1058
1059  // Issue diagnostic and remove storage class if present.
1060  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1061    if (DS.getStorageClassSpecLoc().isValid())
1062      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1063    else
1064      Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
1065    DS.ClearStorageClassSpecs();
1066  }
1067
1068  // Issue diagnostic and remove function specfier if present.
1069  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
1070    if (DS.isInlineSpecified())
1071      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
1072    if (DS.isVirtualSpecified())
1073      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
1074    if (DS.isExplicitSpecified())
1075      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
1076    DS.ClearFunctionSpecs();
1077  }
1078}
1079
1080/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
1081/// specified token is valid after the identifier in a declarator which
1082/// immediately follows the declspec.  For example, these things are valid:
1083///
1084///      int x   [             4];         // direct-declarator
1085///      int x   (             int y);     // direct-declarator
1086///  int(int x   )                         // direct-declarator
1087///      int x   ;                         // simple-declaration
1088///      int x   =             17;         // init-declarator-list
1089///      int x   ,             y;          // init-declarator-list
1090///      int x   __asm__       ("foo");    // init-declarator-list
1091///      int x   :             4;          // struct-declarator
1092///      int x   {             5};         // C++'0x unified initializers
1093///
1094/// This is not, because 'x' does not immediately follow the declspec (though
1095/// ')' happens to be valid anyway).
1096///    int (x)
1097///
1098static bool isValidAfterIdentifierInDeclarator(const Token &T) {
1099  return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
1100         T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
1101         T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
1102}
1103
1104
1105/// ParseImplicitInt - This method is called when we have an non-typename
1106/// identifier in a declspec (which normally terminates the decl spec) when
1107/// the declspec has no type specifier.  In this case, the declspec is either
1108/// malformed or is "implicit int" (in K&R and C89).
1109///
1110/// This method handles diagnosing this prettily and returns false if the
1111/// declspec is done being processed.  If it recovers and thinks there may be
1112/// other pieces of declspec after it, it returns true.
1113///
1114bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1115                              const ParsedTemplateInfo &TemplateInfo,
1116                              AccessSpecifier AS) {
1117  assert(Tok.is(tok::identifier) && "should have identifier");
1118
1119  SourceLocation Loc = Tok.getLocation();
1120  // If we see an identifier that is not a type name, we normally would
1121  // parse it as the identifer being declared.  However, when a typename
1122  // is typo'd or the definition is not included, this will incorrectly
1123  // parse the typename as the identifier name and fall over misparsing
1124  // later parts of the diagnostic.
1125  //
1126  // As such, we try to do some look-ahead in cases where this would
1127  // otherwise be an "implicit-int" case to see if this is invalid.  For
1128  // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
1129  // an identifier with implicit int, we'd get a parse error because the
1130  // next token is obviously invalid for a type.  Parse these as a case
1131  // with an invalid type specifier.
1132  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
1133
1134  // Since we know that this either implicit int (which is rare) or an
1135  // error, we'd do lookahead to try to do better recovery.
1136  if (isValidAfterIdentifierInDeclarator(NextToken())) {
1137    // If this token is valid for implicit int, e.g. "static x = 4", then
1138    // we just avoid eating the identifier, so it will be parsed as the
1139    // identifier in the declarator.
1140    return false;
1141  }
1142
1143  // Otherwise, if we don't consume this token, we are going to emit an
1144  // error anyway.  Try to recover from various common problems.  Check
1145  // to see if this was a reference to a tag name without a tag specified.
1146  // This is a common problem in C (saying 'foo' instead of 'struct foo').
1147  //
1148  // C++ doesn't need this, and isTagName doesn't take SS.
1149  if (SS == 0) {
1150    const char *TagName = 0, *FixitTagName = 0;
1151    tok::TokenKind TagKind = tok::unknown;
1152
1153    switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
1154      default: break;
1155      case DeclSpec::TST_enum:
1156        TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
1157      case DeclSpec::TST_union:
1158        TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
1159      case DeclSpec::TST_struct:
1160        TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
1161      case DeclSpec::TST_class:
1162        TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
1163    }
1164
1165    if (TagName) {
1166      Diag(Loc, diag::err_use_of_tag_name_without_tag)
1167        << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus
1168        << FixItHint::CreateInsertion(Tok.getLocation(),FixitTagName);
1169
1170      // Parse this as a tag as if the missing tag were present.
1171      if (TagKind == tok::kw_enum)
1172        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1173      else
1174        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
1175      return true;
1176    }
1177  }
1178
1179  // This is almost certainly an invalid type name. Let the action emit a
1180  // diagnostic and attempt to recover.
1181  ParsedType T;
1182  if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
1183                                      getCurScope(), SS, T)) {
1184    // The action emitted a diagnostic, so we don't have to.
1185    if (T) {
1186      // The action has suggested that the type T could be used. Set that as
1187      // the type in the declaration specifiers, consume the would-be type
1188      // name token, and we're done.
1189      const char *PrevSpec;
1190      unsigned DiagID;
1191      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
1192      DS.SetRangeEnd(Tok.getLocation());
1193      ConsumeToken();
1194
1195      // There may be other declaration specifiers after this.
1196      return true;
1197    }
1198
1199    // Fall through; the action had no suggestion for us.
1200  } else {
1201    // The action did not emit a diagnostic, so emit one now.
1202    SourceRange R;
1203    if (SS) R = SS->getRange();
1204    Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
1205  }
1206
1207  // Mark this as an error.
1208  const char *PrevSpec;
1209  unsigned DiagID;
1210  DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
1211  DS.SetRangeEnd(Tok.getLocation());
1212  ConsumeToken();
1213
1214  // TODO: Could inject an invalid typedef decl in an enclosing scope to
1215  // avoid rippling error messages on subsequent uses of the same type,
1216  // could be useful if #include was forgotten.
1217  return false;
1218}
1219
1220/// \brief Determine the declaration specifier context from the declarator
1221/// context.
1222///
1223/// \param Context the declarator context, which is one of the
1224/// Declarator::TheContext enumerator values.
1225Parser::DeclSpecContext
1226Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
1227  if (Context == Declarator::MemberContext)
1228    return DSC_class;
1229  if (Context == Declarator::FileContext)
1230    return DSC_top_level;
1231  return DSC_normal;
1232}
1233
1234/// ParseDeclarationSpecifiers
1235///       declaration-specifiers: [C99 6.7]
1236///         storage-class-specifier declaration-specifiers[opt]
1237///         type-specifier declaration-specifiers[opt]
1238/// [C99]   function-specifier declaration-specifiers[opt]
1239/// [GNU]   attributes declaration-specifiers[opt]
1240///
1241///       storage-class-specifier: [C99 6.7.1]
1242///         'typedef'
1243///         'extern'
1244///         'static'
1245///         'auto'
1246///         'register'
1247/// [C++]   'mutable'
1248/// [GNU]   '__thread'
1249///       function-specifier: [C99 6.7.4]
1250/// [C99]   'inline'
1251/// [C++]   'virtual'
1252/// [C++]   'explicit'
1253/// [OpenCL] '__kernel'
1254///       'friend': [C++ dcl.friend]
1255///       'constexpr': [C++0x dcl.constexpr]
1256
1257///
1258void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
1259                                        const ParsedTemplateInfo &TemplateInfo,
1260                                        AccessSpecifier AS,
1261                                        DeclSpecContext DSContext) {
1262  if (DS.getSourceRange().isInvalid()) {
1263    DS.SetRangeStart(Tok.getLocation());
1264    DS.SetRangeEnd(Tok.getLocation());
1265  }
1266
1267  while (1) {
1268    bool isInvalid = false;
1269    const char *PrevSpec = 0;
1270    unsigned DiagID = 0;
1271
1272    SourceLocation Loc = Tok.getLocation();
1273
1274    switch (Tok.getKind()) {
1275    default:
1276    DoneWithDeclSpec:
1277      // If this is not a declaration specifier token, we're done reading decl
1278      // specifiers.  First verify that DeclSpec's are consistent.
1279      DS.Finish(Diags, PP);
1280      return;
1281
1282    case tok::code_completion: {
1283      Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
1284      if (DS.hasTypeSpecifier()) {
1285        bool AllowNonIdentifiers
1286          = (getCurScope()->getFlags() & (Scope::ControlScope |
1287                                          Scope::BlockScope |
1288                                          Scope::TemplateParamScope |
1289                                          Scope::FunctionPrototypeScope |
1290                                          Scope::AtCatchScope)) == 0;
1291        bool AllowNestedNameSpecifiers
1292          = DSContext == DSC_top_level ||
1293            (DSContext == DSC_class && DS.isFriendSpecified());
1294
1295        Actions.CodeCompleteDeclSpec(getCurScope(), DS,
1296                                     AllowNonIdentifiers,
1297                                     AllowNestedNameSpecifiers);
1298        ConsumeCodeCompletionToken();
1299        return;
1300      }
1301
1302      if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
1303        CCC = Sema::PCC_LocalDeclarationSpecifiers;
1304      else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
1305        CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
1306                                    : Sema::PCC_Template;
1307      else if (DSContext == DSC_class)
1308        CCC = Sema::PCC_Class;
1309      else if (ObjCImpDecl)
1310        CCC = Sema::PCC_ObjCImplementation;
1311
1312      Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
1313      ConsumeCodeCompletionToken();
1314      return;
1315    }
1316
1317    case tok::coloncolon: // ::foo::bar
1318      // C++ scope specifier.  Annotate and loop, or bail out on error.
1319      if (TryAnnotateCXXScopeToken(true)) {
1320        if (!DS.hasTypeSpecifier())
1321          DS.SetTypeSpecError();
1322        goto DoneWithDeclSpec;
1323      }
1324      if (Tok.is(tok::coloncolon)) // ::new or ::delete
1325        goto DoneWithDeclSpec;
1326      continue;
1327
1328    case tok::annot_cxxscope: {
1329      if (DS.hasTypeSpecifier())
1330        goto DoneWithDeclSpec;
1331
1332      CXXScopeSpec SS;
1333      Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1334                                                   Tok.getAnnotationRange(),
1335                                                   SS);
1336
1337      // We are looking for a qualified typename.
1338      Token Next = NextToken();
1339      if (Next.is(tok::annot_template_id) &&
1340          static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
1341            ->Kind == TNK_Type_template) {
1342        // We have a qualified template-id, e.g., N::A<int>
1343
1344        // C++ [class.qual]p2:
1345        //   In a lookup in which the constructor is an acceptable lookup
1346        //   result and the nested-name-specifier nominates a class C:
1347        //
1348        //     - if the name specified after the
1349        //       nested-name-specifier, when looked up in C, is the
1350        //       injected-class-name of C (Clause 9), or
1351        //
1352        //     - if the name specified after the nested-name-specifier
1353        //       is the same as the identifier or the
1354        //       simple-template-id's template-name in the last
1355        //       component of the nested-name-specifier,
1356        //
1357        //   the name is instead considered to name the constructor of
1358        //   class C.
1359        //
1360        // Thus, if the template-name is actually the constructor
1361        // name, then the code is ill-formed; this interpretation is
1362        // reinforced by the NAD status of core issue 635.
1363        TemplateIdAnnotation *TemplateId
1364          = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue());
1365        if ((DSContext == DSC_top_level ||
1366             (DSContext == DSC_class && DS.isFriendSpecified())) &&
1367            TemplateId->Name &&
1368            Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
1369          if (isConstructorDeclarator()) {
1370            // The user meant this to be an out-of-line constructor
1371            // definition, but template arguments are not allowed
1372            // there.  Just allow this as a constructor; we'll
1373            // complain about it later.
1374            goto DoneWithDeclSpec;
1375          }
1376
1377          // The user meant this to name a type, but it actually names
1378          // a constructor with some extraneous template
1379          // arguments. Complain, then parse it as a type as the user
1380          // intended.
1381          Diag(TemplateId->TemplateNameLoc,
1382               diag::err_out_of_line_template_id_names_constructor)
1383            << TemplateId->Name;
1384        }
1385
1386        DS.getTypeSpecScope() = SS;
1387        ConsumeToken(); // The C++ scope.
1388        assert(Tok.is(tok::annot_template_id) &&
1389               "ParseOptionalCXXScopeSpecifier not working");
1390        AnnotateTemplateIdTokenAsType();
1391        continue;
1392      }
1393
1394      if (Next.is(tok::annot_typename)) {
1395        DS.getTypeSpecScope() = SS;
1396        ConsumeToken(); // The C++ scope.
1397        if (Tok.getAnnotationValue()) {
1398          ParsedType T = getTypeAnnotation(Tok);
1399          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1400                                         Tok.getAnnotationEndLoc(),
1401                                         PrevSpec, DiagID, T);
1402        }
1403        else
1404          DS.SetTypeSpecError();
1405        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1406        ConsumeToken(); // The typename
1407      }
1408
1409      if (Next.isNot(tok::identifier))
1410        goto DoneWithDeclSpec;
1411
1412      // If we're in a context where the identifier could be a class name,
1413      // check whether this is a constructor declaration.
1414      if ((DSContext == DSC_top_level ||
1415           (DSContext == DSC_class && DS.isFriendSpecified())) &&
1416          Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
1417                                     &SS)) {
1418        if (isConstructorDeclarator())
1419          goto DoneWithDeclSpec;
1420
1421        // As noted in C++ [class.qual]p2 (cited above), when the name
1422        // of the class is qualified in a context where it could name
1423        // a constructor, its a constructor name. However, we've
1424        // looked at the declarator, and the user probably meant this
1425        // to be a type. Complain that it isn't supposed to be treated
1426        // as a type, then proceed to parse it as a type.
1427        Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
1428          << Next.getIdentifierInfo();
1429      }
1430
1431      ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
1432                                               Next.getLocation(),
1433                                               getCurScope(), &SS,
1434                                               false, false, ParsedType(),
1435                                               /*NonTrivialSourceInfo=*/true);
1436
1437      // If the referenced identifier is not a type, then this declspec is
1438      // erroneous: We already checked about that it has no type specifier, and
1439      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
1440      // typename.
1441      if (TypeRep == 0) {
1442        ConsumeToken();   // Eat the scope spec so the identifier is current.
1443        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
1444        goto DoneWithDeclSpec;
1445      }
1446
1447      DS.getTypeSpecScope() = SS;
1448      ConsumeToken(); // The C++ scope.
1449
1450      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1451                                     DiagID, TypeRep);
1452      if (isInvalid)
1453        break;
1454
1455      DS.SetRangeEnd(Tok.getLocation());
1456      ConsumeToken(); // The typename.
1457
1458      continue;
1459    }
1460
1461    case tok::annot_typename: {
1462      if (Tok.getAnnotationValue()) {
1463        ParsedType T = getTypeAnnotation(Tok);
1464        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1465                                       DiagID, T);
1466      } else
1467        DS.SetTypeSpecError();
1468
1469      if (isInvalid)
1470        break;
1471
1472      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1473      ConsumeToken(); // The typename
1474
1475      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1476      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1477      // Objective-C interface.
1478      if (Tok.is(tok::less) && getLang().ObjC1)
1479        ParseObjCProtocolQualifiers(DS);
1480
1481      continue;
1482    }
1483
1484    case tok::kw___is_signed:
1485      // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
1486      // typically treats it as a trait. If we see __is_signed as it appears
1487      // in libstdc++, e.g.,
1488      //
1489      //   static const bool __is_signed;
1490      //
1491      // then treat __is_signed as an identifier rather than as a keyword.
1492      if (DS.getTypeSpecType() == TST_bool &&
1493          DS.getTypeQualifiers() == DeclSpec::TQ_const &&
1494          DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1495        Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
1496        Tok.setKind(tok::identifier);
1497      }
1498
1499      // We're done with the declaration-specifiers.
1500      goto DoneWithDeclSpec;
1501
1502      // typedef-name
1503    case tok::identifier: {
1504      // In C++, check to see if this is a scope specifier like foo::bar::, if
1505      // so handle it as such.  This is important for ctor parsing.
1506      if (getLang().CPlusPlus) {
1507        if (TryAnnotateCXXScopeToken(true)) {
1508          if (!DS.hasTypeSpecifier())
1509            DS.SetTypeSpecError();
1510          goto DoneWithDeclSpec;
1511        }
1512        if (!Tok.is(tok::identifier))
1513          continue;
1514      }
1515
1516      // This identifier can only be a typedef name if we haven't already seen
1517      // a type-specifier.  Without this check we misparse:
1518      //  typedef int X; struct Y { short X; };  as 'short int'.
1519      if (DS.hasTypeSpecifier())
1520        goto DoneWithDeclSpec;
1521
1522      // Check for need to substitute AltiVec keyword tokens.
1523      if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1524        break;
1525
1526      // It has to be available as a typedef too!
1527      ParsedType TypeRep =
1528        Actions.getTypeName(*Tok.getIdentifierInfo(),
1529                            Tok.getLocation(), getCurScope());
1530
1531      // If this is not a typedef name, don't parse it as part of the declspec,
1532      // it must be an implicit int or an error.
1533      if (!TypeRep) {
1534        if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
1535        goto DoneWithDeclSpec;
1536      }
1537
1538      // If we're in a context where the identifier could be a class name,
1539      // check whether this is a constructor declaration.
1540      if (getLang().CPlusPlus && DSContext == DSC_class &&
1541          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
1542          isConstructorDeclarator())
1543        goto DoneWithDeclSpec;
1544
1545      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1546                                     DiagID, TypeRep);
1547      if (isInvalid)
1548        break;
1549
1550      DS.SetRangeEnd(Tok.getLocation());
1551      ConsumeToken(); // The identifier
1552
1553      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1554      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1555      // Objective-C interface.
1556      if (Tok.is(tok::less) && getLang().ObjC1)
1557        ParseObjCProtocolQualifiers(DS);
1558
1559      // Need to support trailing type qualifiers (e.g. "id<p> const").
1560      // If a type specifier follows, it will be diagnosed elsewhere.
1561      continue;
1562    }
1563
1564      // type-name
1565    case tok::annot_template_id: {
1566      TemplateIdAnnotation *TemplateId
1567        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1568      if (TemplateId->Kind != TNK_Type_template) {
1569        // This template-id does not refer to a type name, so we're
1570        // done with the type-specifiers.
1571        goto DoneWithDeclSpec;
1572      }
1573
1574      // If we're in a context where the template-id could be a
1575      // constructor name or specialization, check whether this is a
1576      // constructor declaration.
1577      if (getLang().CPlusPlus && DSContext == DSC_class &&
1578          Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
1579          isConstructorDeclarator())
1580        goto DoneWithDeclSpec;
1581
1582      // Turn the template-id annotation token into a type annotation
1583      // token, then try again to parse it as a type-specifier.
1584      AnnotateTemplateIdTokenAsType();
1585      continue;
1586    }
1587
1588    // GNU attributes support.
1589    case tok::kw___attribute:
1590      ParseGNUAttributes(DS.getAttributes());
1591      continue;
1592
1593    // Microsoft declspec support.
1594    case tok::kw___declspec:
1595      ParseMicrosoftDeclSpec(DS.getAttributes());
1596      continue;
1597
1598    // Microsoft single token adornments.
1599    case tok::kw___forceinline:
1600      // FIXME: Add handling here!
1601      break;
1602
1603    case tok::kw___ptr64:
1604    case tok::kw___w64:
1605    case tok::kw___cdecl:
1606    case tok::kw___stdcall:
1607    case tok::kw___fastcall:
1608    case tok::kw___thiscall:
1609      ParseMicrosoftTypeAttributes(DS.getAttributes());
1610      continue;
1611
1612    // Borland single token adornments.
1613    case tok::kw___pascal:
1614      ParseBorlandTypeAttributes(DS.getAttributes());
1615      continue;
1616
1617    // OpenCL single token adornments.
1618    case tok::kw___kernel:
1619      ParseOpenCLAttributes(DS.getAttributes());
1620      continue;
1621
1622    // storage-class-specifier
1623    case tok::kw_typedef:
1624      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
1625                                         DiagID, getLang());
1626      break;
1627    case tok::kw_extern:
1628      if (DS.isThreadSpecified())
1629        Diag(Tok, diag::ext_thread_before) << "extern";
1630      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1631                                         DiagID, getLang());
1632      break;
1633    case tok::kw___private_extern__:
1634      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1635                                         PrevSpec, DiagID, getLang());
1636      break;
1637    case tok::kw_static:
1638      if (DS.isThreadSpecified())
1639        Diag(Tok, diag::ext_thread_before) << "static";
1640      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1641                                         DiagID, getLang());
1642      break;
1643    case tok::kw_auto:
1644      if (getLang().CPlusPlus0x) {
1645        if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
1646          isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1647                                           DiagID, getLang());
1648          if (!isInvalid)
1649            Diag(Tok, diag::auto_storage_class)
1650              << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
1651        }
1652        else
1653          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1654                                         DiagID);
1655      }
1656      else
1657        isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1658                                           DiagID, getLang());
1659      break;
1660    case tok::kw_register:
1661      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1662                                         DiagID, getLang());
1663      break;
1664    case tok::kw_mutable:
1665      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1666                                         DiagID, getLang());
1667      break;
1668    case tok::kw___thread:
1669      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1670      break;
1671
1672    // function-specifier
1673    case tok::kw_inline:
1674      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1675      break;
1676    case tok::kw_virtual:
1677      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1678      break;
1679    case tok::kw_explicit:
1680      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1681      break;
1682
1683    // friend
1684    case tok::kw_friend:
1685      if (DSContext == DSC_class)
1686        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1687      else {
1688        PrevSpec = ""; // not actually used by the diagnostic
1689        DiagID = diag::err_friend_invalid_in_context;
1690        isInvalid = true;
1691      }
1692      break;
1693
1694    // constexpr
1695    case tok::kw_constexpr:
1696      isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
1697      break;
1698
1699    // type-specifier
1700    case tok::kw_short:
1701      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1702                                      DiagID);
1703      break;
1704    case tok::kw_long:
1705      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1706        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1707                                        DiagID);
1708      else
1709        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1710                                        DiagID);
1711      break;
1712    case tok::kw___int64:
1713        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1714                                        DiagID);
1715      break;
1716    case tok::kw_signed:
1717      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1718                                     DiagID);
1719      break;
1720    case tok::kw_unsigned:
1721      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1722                                     DiagID);
1723      break;
1724    case tok::kw__Complex:
1725      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1726                                        DiagID);
1727      break;
1728    case tok::kw__Imaginary:
1729      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1730                                        DiagID);
1731      break;
1732    case tok::kw_void:
1733      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1734                                     DiagID);
1735      break;
1736    case tok::kw_char:
1737      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1738                                     DiagID);
1739      break;
1740    case tok::kw_int:
1741      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1742                                     DiagID);
1743      break;
1744    case tok::kw_float:
1745      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1746                                     DiagID);
1747      break;
1748    case tok::kw_double:
1749      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1750                                     DiagID);
1751      break;
1752    case tok::kw_wchar_t:
1753      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1754                                     DiagID);
1755      break;
1756    case tok::kw_char16_t:
1757      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1758                                     DiagID);
1759      break;
1760    case tok::kw_char32_t:
1761      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1762                                     DiagID);
1763      break;
1764    case tok::kw_bool:
1765    case tok::kw__Bool:
1766      if (Tok.is(tok::kw_bool) &&
1767          DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
1768          DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1769        PrevSpec = ""; // Not used by the diagnostic.
1770        DiagID = diag::err_bool_redeclaration;
1771        // For better error recovery.
1772        Tok.setKind(tok::identifier);
1773        isInvalid = true;
1774      } else {
1775        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1776                                       DiagID);
1777      }
1778      break;
1779    case tok::kw__Decimal32:
1780      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1781                                     DiagID);
1782      break;
1783    case tok::kw__Decimal64:
1784      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1785                                     DiagID);
1786      break;
1787    case tok::kw__Decimal128:
1788      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1789                                     DiagID);
1790      break;
1791    case tok::kw___vector:
1792      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1793      break;
1794    case tok::kw___pixel:
1795      isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1796      break;
1797    case tok::kw___unknown_anytype:
1798      isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
1799                                     PrevSpec, DiagID);
1800      break;
1801
1802    // class-specifier:
1803    case tok::kw_class:
1804    case tok::kw_struct:
1805    case tok::kw_union: {
1806      tok::TokenKind Kind = Tok.getKind();
1807      ConsumeToken();
1808      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1809      continue;
1810    }
1811
1812    // enum-specifier:
1813    case tok::kw_enum:
1814      ConsumeToken();
1815      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1816      continue;
1817
1818    // cv-qualifier:
1819    case tok::kw_const:
1820      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1821                                 getLang());
1822      break;
1823    case tok::kw_volatile:
1824      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1825                                 getLang());
1826      break;
1827    case tok::kw_restrict:
1828      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1829                                 getLang());
1830      break;
1831
1832    // C++ typename-specifier:
1833    case tok::kw_typename:
1834      if (TryAnnotateTypeOrScopeToken()) {
1835        DS.SetTypeSpecError();
1836        goto DoneWithDeclSpec;
1837      }
1838      if (!Tok.is(tok::kw_typename))
1839        continue;
1840      break;
1841
1842    // GNU typeof support.
1843    case tok::kw_typeof:
1844      ParseTypeofSpecifier(DS);
1845      continue;
1846
1847    case tok::kw_decltype:
1848      ParseDecltypeSpecifier(DS);
1849      continue;
1850
1851    // OpenCL qualifiers:
1852    case tok::kw_private:
1853      if (!getLang().OpenCL)
1854        goto DoneWithDeclSpec;
1855    case tok::kw___private:
1856    case tok::kw___global:
1857    case tok::kw___local:
1858    case tok::kw___constant:
1859    case tok::kw___read_only:
1860    case tok::kw___write_only:
1861    case tok::kw___read_write:
1862      ParseOpenCLQualifiers(DS);
1863      break;
1864
1865    case tok::less:
1866      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1867      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
1868      // but we support it.
1869      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1870        goto DoneWithDeclSpec;
1871
1872      if (!ParseObjCProtocolQualifiers(DS))
1873        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1874          << FixItHint::CreateInsertion(Loc, "id")
1875          << SourceRange(Loc, DS.getSourceRange().getEnd());
1876
1877      // Need to support trailing type qualifiers (e.g. "id<p> const").
1878      // If a type specifier follows, it will be diagnosed elsewhere.
1879      continue;
1880    }
1881    // If the specifier wasn't legal, issue a diagnostic.
1882    if (isInvalid) {
1883      assert(PrevSpec && "Method did not return previous specifier!");
1884      assert(DiagID);
1885
1886      if (DiagID == diag::ext_duplicate_declspec)
1887        Diag(Tok, DiagID)
1888          << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
1889      else
1890        Diag(Tok, DiagID) << PrevSpec;
1891    }
1892
1893    DS.SetRangeEnd(Tok.getLocation());
1894    if (DiagID != diag::err_bool_redeclaration)
1895      ConsumeToken();
1896  }
1897}
1898
1899/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1900/// primarily follow the C++ grammar with additions for C99 and GNU,
1901/// which together subsume the C grammar. Note that the C++
1902/// type-specifier also includes the C type-qualifier (for const,
1903/// volatile, and C99 restrict). Returns true if a type-specifier was
1904/// found (and parsed), false otherwise.
1905///
1906///       type-specifier: [C++ 7.1.5]
1907///         simple-type-specifier
1908///         class-specifier
1909///         enum-specifier
1910///         elaborated-type-specifier  [TODO]
1911///         cv-qualifier
1912///
1913///       cv-qualifier: [C++ 7.1.5.1]
1914///         'const'
1915///         'volatile'
1916/// [C99]   'restrict'
1917///
1918///       simple-type-specifier: [ C++ 7.1.5.2]
1919///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
1920///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
1921///         'char'
1922///         'wchar_t'
1923///         'bool'
1924///         'short'
1925///         'int'
1926///         'long'
1927///         'signed'
1928///         'unsigned'
1929///         'float'
1930///         'double'
1931///         'void'
1932/// [C99]   '_Bool'
1933/// [C99]   '_Complex'
1934/// [C99]   '_Imaginary'  // Removed in TC2?
1935/// [GNU]   '_Decimal32'
1936/// [GNU]   '_Decimal64'
1937/// [GNU]   '_Decimal128'
1938/// [GNU]   typeof-specifier
1939/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
1940/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
1941/// [C++0x] 'decltype' ( expression )
1942/// [AltiVec] '__vector'
1943bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1944                                        const char *&PrevSpec,
1945                                        unsigned &DiagID,
1946                                        const ParsedTemplateInfo &TemplateInfo,
1947                                        bool SuppressDeclarations) {
1948  SourceLocation Loc = Tok.getLocation();
1949
1950  switch (Tok.getKind()) {
1951  case tok::identifier:   // foo::bar
1952    // If we already have a type specifier, this identifier is not a type.
1953    if (DS.getTypeSpecType() != DeclSpec::TST_unspecified ||
1954        DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
1955        DS.getTypeSpecSign() != DeclSpec::TSS_unspecified)
1956      return false;
1957    // Check for need to substitute AltiVec keyword tokens.
1958    if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1959      break;
1960    // Fall through.
1961  case tok::kw_typename:  // typename foo::bar
1962    // Annotate typenames and C++ scope specifiers.  If we get one, just
1963    // recurse to handle whatever we get.
1964    if (TryAnnotateTypeOrScopeToken())
1965      return true;
1966    if (Tok.is(tok::identifier))
1967      return false;
1968    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1969                                      TemplateInfo, SuppressDeclarations);
1970  case tok::coloncolon:   // ::foo::bar
1971    if (NextToken().is(tok::kw_new) ||    // ::new
1972        NextToken().is(tok::kw_delete))   // ::delete
1973      return false;
1974
1975    // Annotate typenames and C++ scope specifiers.  If we get one, just
1976    // recurse to handle whatever we get.
1977    if (TryAnnotateTypeOrScopeToken())
1978      return true;
1979    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1980                                      TemplateInfo, SuppressDeclarations);
1981
1982  // simple-type-specifier:
1983  case tok::annot_typename: {
1984    if (ParsedType T = getTypeAnnotation(Tok)) {
1985      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1986                                     Tok.getAnnotationEndLoc(), PrevSpec,
1987                                     DiagID, T);
1988    } else
1989      DS.SetTypeSpecError();
1990    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1991    ConsumeToken(); // The typename
1992
1993    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1994    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1995    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1996    // just a normal reference to a typedef name.
1997    if (Tok.is(tok::less) && getLang().ObjC1)
1998      ParseObjCProtocolQualifiers(DS);
1999
2000    return true;
2001  }
2002
2003  case tok::kw_short:
2004    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
2005    break;
2006  case tok::kw_long:
2007    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2008      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2009                                      DiagID);
2010    else
2011      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2012                                      DiagID);
2013    break;
2014  case tok::kw___int64:
2015      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2016                                      DiagID);
2017    break;
2018  case tok::kw_signed:
2019    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
2020    break;
2021  case tok::kw_unsigned:
2022    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
2023                                   DiagID);
2024    break;
2025  case tok::kw__Complex:
2026    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
2027                                      DiagID);
2028    break;
2029  case tok::kw__Imaginary:
2030    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
2031                                      DiagID);
2032    break;
2033  case tok::kw_void:
2034    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
2035    break;
2036  case tok::kw_char:
2037    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
2038    break;
2039  case tok::kw_int:
2040    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
2041    break;
2042  case tok::kw_float:
2043    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
2044    break;
2045  case tok::kw_double:
2046    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
2047    break;
2048  case tok::kw_wchar_t:
2049    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
2050    break;
2051  case tok::kw_char16_t:
2052    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
2053    break;
2054  case tok::kw_char32_t:
2055    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
2056    break;
2057  case tok::kw_bool:
2058  case tok::kw__Bool:
2059    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
2060    break;
2061  case tok::kw__Decimal32:
2062    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
2063                                   DiagID);
2064    break;
2065  case tok::kw__Decimal64:
2066    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
2067                                   DiagID);
2068    break;
2069  case tok::kw__Decimal128:
2070    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
2071                                   DiagID);
2072    break;
2073  case tok::kw___vector:
2074    isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
2075    break;
2076  case tok::kw___pixel:
2077    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
2078    break;
2079
2080  // class-specifier:
2081  case tok::kw_class:
2082  case tok::kw_struct:
2083  case tok::kw_union: {
2084    tok::TokenKind Kind = Tok.getKind();
2085    ConsumeToken();
2086    ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none,
2087                        SuppressDeclarations);
2088    return true;
2089  }
2090
2091  // enum-specifier:
2092  case tok::kw_enum:
2093    ConsumeToken();
2094    ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none);
2095    return true;
2096
2097  // cv-qualifier:
2098  case tok::kw_const:
2099    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
2100                               DiagID, getLang());
2101    break;
2102  case tok::kw_volatile:
2103    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
2104                               DiagID, getLang());
2105    break;
2106  case tok::kw_restrict:
2107    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
2108                               DiagID, getLang());
2109    break;
2110
2111  // GNU typeof support.
2112  case tok::kw_typeof:
2113    ParseTypeofSpecifier(DS);
2114    return true;
2115
2116  // C++0x decltype support.
2117  case tok::kw_decltype:
2118    ParseDecltypeSpecifier(DS);
2119    return true;
2120
2121  // OpenCL qualifiers:
2122  case tok::kw_private:
2123    if (!getLang().OpenCL)
2124      return false;
2125  case tok::kw___private:
2126  case tok::kw___global:
2127  case tok::kw___local:
2128  case tok::kw___constant:
2129  case tok::kw___read_only:
2130  case tok::kw___write_only:
2131  case tok::kw___read_write:
2132    ParseOpenCLQualifiers(DS);
2133    break;
2134
2135  // C++0x auto support.
2136  case tok::kw_auto:
2137    if (!getLang().CPlusPlus0x)
2138      return false;
2139
2140    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
2141    break;
2142
2143  case tok::kw___ptr64:
2144  case tok::kw___w64:
2145  case tok::kw___cdecl:
2146  case tok::kw___stdcall:
2147  case tok::kw___fastcall:
2148  case tok::kw___thiscall:
2149    ParseMicrosoftTypeAttributes(DS.getAttributes());
2150    return true;
2151
2152  case tok::kw___pascal:
2153    ParseBorlandTypeAttributes(DS.getAttributes());
2154    return true;
2155
2156  default:
2157    // Not a type-specifier; do nothing.
2158    return false;
2159  }
2160
2161  // If the specifier combination wasn't legal, issue a diagnostic.
2162  if (isInvalid) {
2163    assert(PrevSpec && "Method did not return previous specifier!");
2164    // Pick between error or extwarn.
2165    Diag(Tok, DiagID) << PrevSpec;
2166  }
2167  DS.SetRangeEnd(Tok.getLocation());
2168  ConsumeToken(); // whatever we parsed above.
2169  return true;
2170}
2171
2172/// ParseStructDeclaration - Parse a struct declaration without the terminating
2173/// semicolon.
2174///
2175///       struct-declaration:
2176///         specifier-qualifier-list struct-declarator-list
2177/// [GNU]   __extension__ struct-declaration
2178/// [GNU]   specifier-qualifier-list
2179///       struct-declarator-list:
2180///         struct-declarator
2181///         struct-declarator-list ',' struct-declarator
2182/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
2183///       struct-declarator:
2184///         declarator
2185/// [GNU]   declarator attributes[opt]
2186///         declarator[opt] ':' constant-expression
2187/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
2188///
2189void Parser::
2190ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
2191  if (Tok.is(tok::kw___extension__)) {
2192    // __extension__ silences extension warnings in the subexpression.
2193    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
2194    ConsumeToken();
2195    return ParseStructDeclaration(DS, Fields);
2196  }
2197
2198  // Parse the common specifier-qualifiers-list piece.
2199  ParseSpecifierQualifierList(DS);
2200
2201  // If there are no declarators, this is a free-standing declaration
2202  // specifier. Let the actions module cope with it.
2203  if (Tok.is(tok::semi)) {
2204    Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS);
2205    return;
2206  }
2207
2208  // Read struct-declarators until we find the semicolon.
2209  bool FirstDeclarator = true;
2210  while (1) {
2211    ParsingDeclRAIIObject PD(*this);
2212    FieldDeclarator DeclaratorInfo(DS);
2213
2214    // Attributes are only allowed here on successive declarators.
2215    if (!FirstDeclarator)
2216      MaybeParseGNUAttributes(DeclaratorInfo.D);
2217
2218    /// struct-declarator: declarator
2219    /// struct-declarator: declarator[opt] ':' constant-expression
2220    if (Tok.isNot(tok::colon)) {
2221      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2222      ColonProtectionRAIIObject X(*this);
2223      ParseDeclarator(DeclaratorInfo.D);
2224    }
2225
2226    if (Tok.is(tok::colon)) {
2227      ConsumeToken();
2228      ExprResult Res(ParseConstantExpression());
2229      if (Res.isInvalid())
2230        SkipUntil(tok::semi, true, true);
2231      else
2232        DeclaratorInfo.BitfieldSize = Res.release();
2233    }
2234
2235    // If attributes exist after the declarator, parse them.
2236    MaybeParseGNUAttributes(DeclaratorInfo.D);
2237
2238    // We're done with this declarator;  invoke the callback.
2239    Decl *D = Fields.invoke(DeclaratorInfo);
2240    PD.complete(D);
2241
2242    // If we don't have a comma, it is either the end of the list (a ';')
2243    // or an error, bail out.
2244    if (Tok.isNot(tok::comma))
2245      return;
2246
2247    // Consume the comma.
2248    ConsumeToken();
2249
2250    FirstDeclarator = false;
2251  }
2252}
2253
2254/// ParseStructUnionBody
2255///       struct-contents:
2256///         struct-declaration-list
2257/// [EXT]   empty
2258/// [GNU]   "struct-declaration-list" without terminatoring ';'
2259///       struct-declaration-list:
2260///         struct-declaration
2261///         struct-declaration-list struct-declaration
2262/// [OBC]   '@' 'defs' '(' class-name ')'
2263///
2264void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
2265                                  unsigned TagType, Decl *TagDecl) {
2266  PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2267                                      "parsing struct/union body");
2268
2269  SourceLocation LBraceLoc = ConsumeBrace();
2270
2271  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
2272  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2273
2274  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
2275  // C++.
2276  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
2277    Diag(Tok, diag::ext_empty_struct_union)
2278      << (TagType == TST_union);
2279
2280  llvm::SmallVector<Decl *, 32> FieldDecls;
2281
2282  // While we still have something to read, read the declarations in the struct.
2283  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2284    // Each iteration of this loop reads one struct-declaration.
2285
2286    // Check for extraneous top-level semicolon.
2287    if (Tok.is(tok::semi)) {
2288      Diag(Tok, diag::ext_extra_struct_semi)
2289        << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
2290        << FixItHint::CreateRemoval(Tok.getLocation());
2291      ConsumeToken();
2292      continue;
2293    }
2294
2295    // Parse all the comma separated declarators.
2296    DeclSpec DS(AttrFactory);
2297
2298    if (!Tok.is(tok::at)) {
2299      struct CFieldCallback : FieldCallback {
2300        Parser &P;
2301        Decl *TagDecl;
2302        llvm::SmallVectorImpl<Decl *> &FieldDecls;
2303
2304        CFieldCallback(Parser &P, Decl *TagDecl,
2305                       llvm::SmallVectorImpl<Decl *> &FieldDecls) :
2306          P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
2307
2308        virtual Decl *invoke(FieldDeclarator &FD) {
2309          // Install the declarator into the current TagDecl.
2310          Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
2311                              FD.D.getDeclSpec().getSourceRange().getBegin(),
2312                                                 FD.D, FD.BitfieldSize);
2313          FieldDecls.push_back(Field);
2314          return Field;
2315        }
2316      } Callback(*this, TagDecl, FieldDecls);
2317
2318      ParseStructDeclaration(DS, Callback);
2319    } else { // Handle @defs
2320      ConsumeToken();
2321      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
2322        Diag(Tok, diag::err_unexpected_at);
2323        SkipUntil(tok::semi, true);
2324        continue;
2325      }
2326      ConsumeToken();
2327      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
2328      if (!Tok.is(tok::identifier)) {
2329        Diag(Tok, diag::err_expected_ident);
2330        SkipUntil(tok::semi, true);
2331        continue;
2332      }
2333      llvm::SmallVector<Decl *, 16> Fields;
2334      Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
2335                        Tok.getIdentifierInfo(), Fields);
2336      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
2337      ConsumeToken();
2338      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
2339    }
2340
2341    if (Tok.is(tok::semi)) {
2342      ConsumeToken();
2343    } else if (Tok.is(tok::r_brace)) {
2344      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
2345      break;
2346    } else {
2347      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
2348      // Skip to end of block or statement to avoid ext-warning on extra ';'.
2349      SkipUntil(tok::r_brace, true, true);
2350      // If we stopped at a ';', eat it.
2351      if (Tok.is(tok::semi)) ConsumeToken();
2352    }
2353  }
2354
2355  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2356
2357  ParsedAttributes attrs(AttrFactory);
2358  // If attributes exist after struct contents, parse them.
2359  MaybeParseGNUAttributes(attrs);
2360
2361  Actions.ActOnFields(getCurScope(),
2362                      RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
2363                      LBraceLoc, RBraceLoc,
2364                      attrs.getList());
2365  StructScope.Exit();
2366  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc);
2367}
2368
2369/// ParseEnumSpecifier
2370///       enum-specifier: [C99 6.7.2.2]
2371///         'enum' identifier[opt] '{' enumerator-list '}'
2372///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
2373/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
2374///                                                 '}' attributes[opt]
2375///         'enum' identifier
2376/// [GNU]   'enum' attributes[opt] identifier
2377///
2378/// [C++0x] enum-head '{' enumerator-list[opt] '}'
2379/// [C++0x] enum-head '{' enumerator-list ','  '}'
2380///
2381///       enum-head: [C++0x]
2382///         enum-key attributes[opt] identifier[opt] enum-base[opt]
2383///         enum-key attributes[opt] nested-name-specifier identifier enum-base[opt]
2384///
2385///       enum-key: [C++0x]
2386///         'enum'
2387///         'enum' 'class'
2388///         'enum' 'struct'
2389///
2390///       enum-base: [C++0x]
2391///         ':' type-specifier-seq
2392///
2393/// [C++] elaborated-type-specifier:
2394/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
2395///
2396void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
2397                                const ParsedTemplateInfo &TemplateInfo,
2398                                AccessSpecifier AS) {
2399  // Parse the tag portion of this.
2400  if (Tok.is(tok::code_completion)) {
2401    // Code completion for an enum name.
2402    Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
2403    ConsumeCodeCompletionToken();
2404  }
2405
2406  // If attributes exist after tag, parse them.
2407  ParsedAttributes attrs(AttrFactory);
2408  MaybeParseGNUAttributes(attrs);
2409
2410  CXXScopeSpec &SS = DS.getTypeSpecScope();
2411  if (getLang().CPlusPlus) {
2412    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false))
2413      return;
2414
2415    if (SS.isSet() && Tok.isNot(tok::identifier)) {
2416      Diag(Tok, diag::err_expected_ident);
2417      if (Tok.isNot(tok::l_brace)) {
2418        // Has no name and is not a definition.
2419        // Skip the rest of this declarator, up until the comma or semicolon.
2420        SkipUntil(tok::comma, true);
2421        return;
2422      }
2423    }
2424  }
2425
2426  bool AllowFixedUnderlyingType = getLang().CPlusPlus0x || getLang().Microsoft;
2427  bool IsScopedEnum = false;
2428  bool IsScopedUsingClassTag = false;
2429
2430  if (getLang().CPlusPlus0x &&
2431      (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
2432    IsScopedEnum = true;
2433    IsScopedUsingClassTag = Tok.is(tok::kw_class);
2434    ConsumeToken();
2435  }
2436
2437  // Must have either 'enum name' or 'enum {...}'.
2438  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
2439      (AllowFixedUnderlyingType && Tok.isNot(tok::colon))) {
2440    Diag(Tok, diag::err_expected_ident_lbrace);
2441
2442    // Skip the rest of this declarator, up until the comma or semicolon.
2443    SkipUntil(tok::comma, true);
2444    return;
2445  }
2446
2447  // If an identifier is present, consume and remember it.
2448  IdentifierInfo *Name = 0;
2449  SourceLocation NameLoc;
2450  if (Tok.is(tok::identifier)) {
2451    Name = Tok.getIdentifierInfo();
2452    NameLoc = ConsumeToken();
2453  }
2454
2455  if (!Name && IsScopedEnum) {
2456    // C++0x 7.2p2: The optional identifier shall not be omitted in the
2457    // declaration of a scoped enumeration.
2458    Diag(Tok, diag::err_scoped_enum_missing_identifier);
2459    IsScopedEnum = false;
2460    IsScopedUsingClassTag = false;
2461  }
2462
2463  TypeResult BaseType;
2464
2465  // Parse the fixed underlying type.
2466  if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
2467    bool PossibleBitfield = false;
2468    if (getCurScope()->getFlags() & Scope::ClassScope) {
2469      // If we're in class scope, this can either be an enum declaration with
2470      // an underlying type, or a declaration of a bitfield member. We try to
2471      // use a simple disambiguation scheme first to catch the common cases
2472      // (integer literal, sizeof); if it's still ambiguous, we then consider
2473      // anything that's a simple-type-specifier followed by '(' as an
2474      // expression. This suffices because function types are not valid
2475      // underlying types anyway.
2476      TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
2477      // If the next token starts an expression, we know we're parsing a
2478      // bit-field. This is the common case.
2479      if (TPR == TPResult::True())
2480        PossibleBitfield = true;
2481      // If the next token starts a type-specifier-seq, it may be either a
2482      // a fixed underlying type or the start of a function-style cast in C++;
2483      // lookahead one more token to see if it's obvious that we have a
2484      // fixed underlying type.
2485      else if (TPR == TPResult::False() &&
2486               GetLookAheadToken(2).getKind() == tok::semi) {
2487        // Consume the ':'.
2488        ConsumeToken();
2489      } else {
2490        // We have the start of a type-specifier-seq, so we have to perform
2491        // tentative parsing to determine whether we have an expression or a
2492        // type.
2493        TentativeParsingAction TPA(*this);
2494
2495        // Consume the ':'.
2496        ConsumeToken();
2497
2498        if ((getLang().CPlusPlus &&
2499             isCXXDeclarationSpecifier() != TPResult::True()) ||
2500            (!getLang().CPlusPlus && !isDeclarationSpecifier(true))) {
2501          // We'll parse this as a bitfield later.
2502          PossibleBitfield = true;
2503          TPA.Revert();
2504        } else {
2505          // We have a type-specifier-seq.
2506          TPA.Commit();
2507        }
2508      }
2509    } else {
2510      // Consume the ':'.
2511      ConsumeToken();
2512    }
2513
2514    if (!PossibleBitfield) {
2515      SourceRange Range;
2516      BaseType = ParseTypeName(&Range);
2517
2518      if (!getLang().CPlusPlus0x)
2519        Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type)
2520          << Range;
2521    }
2522  }
2523
2524  // There are three options here.  If we have 'enum foo;', then this is a
2525  // forward declaration.  If we have 'enum foo {...' then this is a
2526  // definition. Otherwise we have something like 'enum foo xyz', a reference.
2527  //
2528  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
2529  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
2530  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
2531  //
2532  Sema::TagUseKind TUK;
2533  if (Tok.is(tok::l_brace))
2534    TUK = Sema::TUK_Definition;
2535  else if (Tok.is(tok::semi))
2536    TUK = Sema::TUK_Declaration;
2537  else
2538    TUK = Sema::TUK_Reference;
2539
2540  // enums cannot be templates, although they can be referenced from a
2541  // template.
2542  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
2543      TUK != Sema::TUK_Reference) {
2544    Diag(Tok, diag::err_enum_template);
2545
2546    // Skip the rest of this declarator, up until the comma or semicolon.
2547    SkipUntil(tok::comma, true);
2548    return;
2549  }
2550
2551  if (!Name && TUK != Sema::TUK_Definition) {
2552    Diag(Tok, diag::err_enumerator_unnamed_no_def);
2553
2554    // Skip the rest of this declarator, up until the comma or semicolon.
2555    SkipUntil(tok::comma, true);
2556    return;
2557  }
2558
2559  bool Owned = false;
2560  bool IsDependent = false;
2561  const char *PrevSpec = 0;
2562  unsigned DiagID;
2563  Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
2564                                   StartLoc, SS, Name, NameLoc, attrs.getList(),
2565                                   AS,
2566                                   MultiTemplateParamsArg(Actions),
2567                                   Owned, IsDependent, IsScopedEnum,
2568                                   IsScopedUsingClassTag, BaseType);
2569
2570  if (IsDependent) {
2571    // This enum has a dependent nested-name-specifier. Handle it as a
2572    // dependent tag.
2573    if (!Name) {
2574      DS.SetTypeSpecError();
2575      Diag(Tok, diag::err_expected_type_name_after_typename);
2576      return;
2577    }
2578
2579    TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
2580                                                TUK, SS, Name, StartLoc,
2581                                                NameLoc);
2582    if (Type.isInvalid()) {
2583      DS.SetTypeSpecError();
2584      return;
2585    }
2586
2587    if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
2588                           NameLoc.isValid() ? NameLoc : StartLoc,
2589                           PrevSpec, DiagID, Type.get()))
2590      Diag(StartLoc, DiagID) << PrevSpec;
2591
2592    return;
2593  }
2594
2595  if (!TagDecl) {
2596    // The action failed to produce an enumeration tag. If this is a
2597    // definition, consume the entire definition.
2598    if (Tok.is(tok::l_brace)) {
2599      ConsumeBrace();
2600      SkipUntil(tok::r_brace);
2601    }
2602
2603    DS.SetTypeSpecError();
2604    return;
2605  }
2606
2607  if (Tok.is(tok::l_brace))
2608    ParseEnumBody(StartLoc, TagDecl);
2609
2610  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
2611                         NameLoc.isValid() ? NameLoc : StartLoc,
2612                         PrevSpec, DiagID, TagDecl, Owned))
2613    Diag(StartLoc, DiagID) << PrevSpec;
2614}
2615
2616/// ParseEnumBody - Parse a {} enclosed enumerator-list.
2617///       enumerator-list:
2618///         enumerator
2619///         enumerator-list ',' enumerator
2620///       enumerator:
2621///         enumeration-constant
2622///         enumeration-constant '=' constant-expression
2623///       enumeration-constant:
2624///         identifier
2625///
2626void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
2627  // Enter the scope of the enum body and start the definition.
2628  ParseScope EnumScope(this, Scope::DeclScope);
2629  Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
2630
2631  SourceLocation LBraceLoc = ConsumeBrace();
2632
2633  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
2634  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
2635    Diag(Tok, diag::error_empty_enum);
2636
2637  llvm::SmallVector<Decl *, 32> EnumConstantDecls;
2638
2639  Decl *LastEnumConstDecl = 0;
2640
2641  // Parse the enumerator-list.
2642  while (Tok.is(tok::identifier)) {
2643    IdentifierInfo *Ident = Tok.getIdentifierInfo();
2644    SourceLocation IdentLoc = ConsumeToken();
2645
2646    // If attributes exist after the enumerator, parse them.
2647    ParsedAttributes attrs(AttrFactory);
2648    MaybeParseGNUAttributes(attrs);
2649
2650    SourceLocation EqualLoc;
2651    ExprResult AssignedVal;
2652    if (Tok.is(tok::equal)) {
2653      EqualLoc = ConsumeToken();
2654      AssignedVal = ParseConstantExpression();
2655      if (AssignedVal.isInvalid())
2656        SkipUntil(tok::comma, tok::r_brace, true, true);
2657    }
2658
2659    // Install the enumerator constant into EnumDecl.
2660    Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
2661                                                    LastEnumConstDecl,
2662                                                    IdentLoc, Ident,
2663                                                    attrs.getList(), EqualLoc,
2664                                                    AssignedVal.release());
2665    EnumConstantDecls.push_back(EnumConstDecl);
2666    LastEnumConstDecl = EnumConstDecl;
2667
2668    if (Tok.is(tok::identifier)) {
2669      // We're missing a comma between enumerators.
2670      SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2671      Diag(Loc, diag::err_enumerator_list_missing_comma)
2672        << FixItHint::CreateInsertion(Loc, ", ");
2673      continue;
2674    }
2675
2676    if (Tok.isNot(tok::comma))
2677      break;
2678    SourceLocation CommaLoc = ConsumeToken();
2679
2680    if (Tok.isNot(tok::identifier) &&
2681        !(getLang().C99 || getLang().CPlusPlus0x))
2682      Diag(CommaLoc, diag::ext_enumerator_list_comma)
2683        << getLang().CPlusPlus
2684        << FixItHint::CreateRemoval(CommaLoc);
2685  }
2686
2687  // Eat the }.
2688  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2689
2690  // If attributes exist after the identifier list, parse them.
2691  ParsedAttributes attrs(AttrFactory);
2692  MaybeParseGNUAttributes(attrs);
2693
2694  Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
2695                        EnumConstantDecls.data(), EnumConstantDecls.size(),
2696                        getCurScope(), attrs.getList());
2697
2698  EnumScope.Exit();
2699  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, RBraceLoc);
2700}
2701
2702/// isTypeSpecifierQualifier - Return true if the current token could be the
2703/// start of a type-qualifier-list.
2704bool Parser::isTypeQualifier() const {
2705  switch (Tok.getKind()) {
2706  default: return false;
2707
2708    // type-qualifier only in OpenCL
2709  case tok::kw_private:
2710    return getLang().OpenCL;
2711
2712    // type-qualifier
2713  case tok::kw_const:
2714  case tok::kw_volatile:
2715  case tok::kw_restrict:
2716  case tok::kw___private:
2717  case tok::kw___local:
2718  case tok::kw___global:
2719  case tok::kw___constant:
2720  case tok::kw___read_only:
2721  case tok::kw___read_write:
2722  case tok::kw___write_only:
2723    return true;
2724  }
2725}
2726
2727/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2728/// is definitely a type-specifier.  Return false if it isn't part of a type
2729/// specifier or if we're not sure.
2730bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
2731  switch (Tok.getKind()) {
2732  default: return false;
2733    // type-specifiers
2734  case tok::kw_short:
2735  case tok::kw_long:
2736  case tok::kw___int64:
2737  case tok::kw_signed:
2738  case tok::kw_unsigned:
2739  case tok::kw__Complex:
2740  case tok::kw__Imaginary:
2741  case tok::kw_void:
2742  case tok::kw_char:
2743  case tok::kw_wchar_t:
2744  case tok::kw_char16_t:
2745  case tok::kw_char32_t:
2746  case tok::kw_int:
2747  case tok::kw_float:
2748  case tok::kw_double:
2749  case tok::kw_bool:
2750  case tok::kw__Bool:
2751  case tok::kw__Decimal32:
2752  case tok::kw__Decimal64:
2753  case tok::kw__Decimal128:
2754  case tok::kw___vector:
2755
2756    // struct-or-union-specifier (C99) or class-specifier (C++)
2757  case tok::kw_class:
2758  case tok::kw_struct:
2759  case tok::kw_union:
2760    // enum-specifier
2761  case tok::kw_enum:
2762
2763    // typedef-name
2764  case tok::annot_typename:
2765    return true;
2766  }
2767}
2768
2769/// isTypeSpecifierQualifier - Return true if the current token could be the
2770/// start of a specifier-qualifier-list.
2771bool Parser::isTypeSpecifierQualifier() {
2772  switch (Tok.getKind()) {
2773  default: return false;
2774
2775  case tok::identifier:   // foo::bar
2776    if (TryAltiVecVectorToken())
2777      return true;
2778    // Fall through.
2779  case tok::kw_typename:  // typename T::type
2780    // Annotate typenames and C++ scope specifiers.  If we get one, just
2781    // recurse to handle whatever we get.
2782    if (TryAnnotateTypeOrScopeToken())
2783      return true;
2784    if (Tok.is(tok::identifier))
2785      return false;
2786    return isTypeSpecifierQualifier();
2787
2788  case tok::coloncolon:   // ::foo::bar
2789    if (NextToken().is(tok::kw_new) ||    // ::new
2790        NextToken().is(tok::kw_delete))   // ::delete
2791      return false;
2792
2793    if (TryAnnotateTypeOrScopeToken())
2794      return true;
2795    return isTypeSpecifierQualifier();
2796
2797    // GNU attributes support.
2798  case tok::kw___attribute:
2799    // GNU typeof support.
2800  case tok::kw_typeof:
2801
2802    // type-specifiers
2803  case tok::kw_short:
2804  case tok::kw_long:
2805  case tok::kw___int64:
2806  case tok::kw_signed:
2807  case tok::kw_unsigned:
2808  case tok::kw__Complex:
2809  case tok::kw__Imaginary:
2810  case tok::kw_void:
2811  case tok::kw_char:
2812  case tok::kw_wchar_t:
2813  case tok::kw_char16_t:
2814  case tok::kw_char32_t:
2815  case tok::kw_int:
2816  case tok::kw_float:
2817  case tok::kw_double:
2818  case tok::kw_bool:
2819  case tok::kw__Bool:
2820  case tok::kw__Decimal32:
2821  case tok::kw__Decimal64:
2822  case tok::kw__Decimal128:
2823  case tok::kw___vector:
2824
2825    // struct-or-union-specifier (C99) or class-specifier (C++)
2826  case tok::kw_class:
2827  case tok::kw_struct:
2828  case tok::kw_union:
2829    // enum-specifier
2830  case tok::kw_enum:
2831
2832    // type-qualifier
2833  case tok::kw_const:
2834  case tok::kw_volatile:
2835  case tok::kw_restrict:
2836
2837    // typedef-name
2838  case tok::annot_typename:
2839    return true;
2840
2841    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2842  case tok::less:
2843    return getLang().ObjC1;
2844
2845  case tok::kw___cdecl:
2846  case tok::kw___stdcall:
2847  case tok::kw___fastcall:
2848  case tok::kw___thiscall:
2849  case tok::kw___w64:
2850  case tok::kw___ptr64:
2851  case tok::kw___pascal:
2852
2853  case tok::kw___private:
2854  case tok::kw___local:
2855  case tok::kw___global:
2856  case tok::kw___constant:
2857  case tok::kw___read_only:
2858  case tok::kw___read_write:
2859  case tok::kw___write_only:
2860
2861    return true;
2862
2863  case tok::kw_private:
2864    return getLang().OpenCL;
2865  }
2866}
2867
2868/// isDeclarationSpecifier() - Return true if the current token is part of a
2869/// declaration specifier.
2870///
2871/// \param DisambiguatingWithExpression True to indicate that the purpose of
2872/// this check is to disambiguate between an expression and a declaration.
2873bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
2874  switch (Tok.getKind()) {
2875  default: return false;
2876
2877  case tok::kw_private:
2878    return getLang().OpenCL;
2879
2880  case tok::identifier:   // foo::bar
2881    // Unfortunate hack to support "Class.factoryMethod" notation.
2882    if (getLang().ObjC1 && NextToken().is(tok::period))
2883      return false;
2884    if (TryAltiVecVectorToken())
2885      return true;
2886    // Fall through.
2887  case tok::kw_typename: // typename T::type
2888    // Annotate typenames and C++ scope specifiers.  If we get one, just
2889    // recurse to handle whatever we get.
2890    if (TryAnnotateTypeOrScopeToken())
2891      return true;
2892    if (Tok.is(tok::identifier))
2893      return false;
2894
2895    // If we're in Objective-C and we have an Objective-C class type followed
2896    // by an identifier and then either ':' or ']', in a place where an
2897    // expression is permitted, then this is probably a class message send
2898    // missing the initial '['. In this case, we won't consider this to be
2899    // the start of a declaration.
2900    if (DisambiguatingWithExpression &&
2901        isStartOfObjCClassMessageMissingOpenBracket())
2902      return false;
2903
2904    return isDeclarationSpecifier();
2905
2906  case tok::coloncolon:   // ::foo::bar
2907    if (NextToken().is(tok::kw_new) ||    // ::new
2908        NextToken().is(tok::kw_delete))   // ::delete
2909      return false;
2910
2911    // Annotate typenames and C++ scope specifiers.  If we get one, just
2912    // recurse to handle whatever we get.
2913    if (TryAnnotateTypeOrScopeToken())
2914      return true;
2915    return isDeclarationSpecifier();
2916
2917    // storage-class-specifier
2918  case tok::kw_typedef:
2919  case tok::kw_extern:
2920  case tok::kw___private_extern__:
2921  case tok::kw_static:
2922  case tok::kw_auto:
2923  case tok::kw_register:
2924  case tok::kw___thread:
2925
2926    // type-specifiers
2927  case tok::kw_short:
2928  case tok::kw_long:
2929  case tok::kw___int64:
2930  case tok::kw_signed:
2931  case tok::kw_unsigned:
2932  case tok::kw__Complex:
2933  case tok::kw__Imaginary:
2934  case tok::kw_void:
2935  case tok::kw_char:
2936  case tok::kw_wchar_t:
2937  case tok::kw_char16_t:
2938  case tok::kw_char32_t:
2939
2940  case tok::kw_int:
2941  case tok::kw_float:
2942  case tok::kw_double:
2943  case tok::kw_bool:
2944  case tok::kw__Bool:
2945  case tok::kw__Decimal32:
2946  case tok::kw__Decimal64:
2947  case tok::kw__Decimal128:
2948  case tok::kw___vector:
2949
2950    // struct-or-union-specifier (C99) or class-specifier (C++)
2951  case tok::kw_class:
2952  case tok::kw_struct:
2953  case tok::kw_union:
2954    // enum-specifier
2955  case tok::kw_enum:
2956
2957    // type-qualifier
2958  case tok::kw_const:
2959  case tok::kw_volatile:
2960  case tok::kw_restrict:
2961
2962    // function-specifier
2963  case tok::kw_inline:
2964  case tok::kw_virtual:
2965  case tok::kw_explicit:
2966
2967    // static_assert-declaration
2968  case tok::kw__Static_assert:
2969
2970    // GNU typeof support.
2971  case tok::kw_typeof:
2972
2973    // GNU attributes.
2974  case tok::kw___attribute:
2975    return true;
2976
2977    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2978  case tok::less:
2979    return getLang().ObjC1;
2980
2981    // typedef-name
2982  case tok::annot_typename:
2983    return !DisambiguatingWithExpression ||
2984           !isStartOfObjCClassMessageMissingOpenBracket();
2985
2986  case tok::kw___declspec:
2987  case tok::kw___cdecl:
2988  case tok::kw___stdcall:
2989  case tok::kw___fastcall:
2990  case tok::kw___thiscall:
2991  case tok::kw___w64:
2992  case tok::kw___ptr64:
2993  case tok::kw___forceinline:
2994  case tok::kw___pascal:
2995
2996  case tok::kw___private:
2997  case tok::kw___local:
2998  case tok::kw___global:
2999  case tok::kw___constant:
3000  case tok::kw___read_only:
3001  case tok::kw___read_write:
3002  case tok::kw___write_only:
3003
3004    return true;
3005  }
3006}
3007
3008bool Parser::isConstructorDeclarator() {
3009  TentativeParsingAction TPA(*this);
3010
3011  // Parse the C++ scope specifier.
3012  CXXScopeSpec SS;
3013  if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) {
3014    TPA.Revert();
3015    return false;
3016  }
3017
3018  // Parse the constructor name.
3019  if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
3020    // We already know that we have a constructor name; just consume
3021    // the token.
3022    ConsumeToken();
3023  } else {
3024    TPA.Revert();
3025    return false;
3026  }
3027
3028  // Current class name must be followed by a left parentheses.
3029  if (Tok.isNot(tok::l_paren)) {
3030    TPA.Revert();
3031    return false;
3032  }
3033  ConsumeParen();
3034
3035  // A right parentheses or ellipsis signals that we have a constructor.
3036  if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
3037    TPA.Revert();
3038    return true;
3039  }
3040
3041  // If we need to, enter the specified scope.
3042  DeclaratorScopeObj DeclScopeObj(*this, SS);
3043  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3044    DeclScopeObj.EnterDeclaratorScope();
3045
3046  // Optionally skip Microsoft attributes.
3047  ParsedAttributes Attrs(AttrFactory);
3048  MaybeParseMicrosoftAttributes(Attrs);
3049
3050  // Check whether the next token(s) are part of a declaration
3051  // specifier, in which case we have the start of a parameter and,
3052  // therefore, we know that this is a constructor.
3053  bool IsConstructor = isDeclarationSpecifier();
3054  TPA.Revert();
3055  return IsConstructor;
3056}
3057
3058/// ParseTypeQualifierListOpt
3059///          type-qualifier-list: [C99 6.7.5]
3060///            type-qualifier
3061/// [vendor]   attributes
3062///              [ only if VendorAttributesAllowed=true ]
3063///            type-qualifier-list type-qualifier
3064/// [vendor]   type-qualifier-list attributes
3065///              [ only if VendorAttributesAllowed=true ]
3066/// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
3067///              [ only if CXX0XAttributesAllowed=true ]
3068/// Note: vendor can be GNU, MS, etc.
3069///
3070void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
3071                                       bool VendorAttributesAllowed,
3072                                       bool CXX0XAttributesAllowed) {
3073  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3074    SourceLocation Loc = Tok.getLocation();
3075    ParsedAttributesWithRange attrs(AttrFactory);
3076    ParseCXX0XAttributes(attrs);
3077    if (CXX0XAttributesAllowed)
3078      DS.takeAttributesFrom(attrs);
3079    else
3080      Diag(Loc, diag::err_attributes_not_allowed);
3081  }
3082
3083  SourceLocation EndLoc;
3084
3085  while (1) {
3086    bool isInvalid = false;
3087    const char *PrevSpec = 0;
3088    unsigned DiagID = 0;
3089    SourceLocation Loc = Tok.getLocation();
3090
3091    switch (Tok.getKind()) {
3092    case tok::code_completion:
3093      Actions.CodeCompleteTypeQualifiers(DS);
3094      ConsumeCodeCompletionToken();
3095      break;
3096
3097    case tok::kw_const:
3098      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
3099                                 getLang());
3100      break;
3101    case tok::kw_volatile:
3102      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3103                                 getLang());
3104      break;
3105    case tok::kw_restrict:
3106      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3107                                 getLang());
3108      break;
3109
3110    // OpenCL qualifiers:
3111    case tok::kw_private:
3112      if (!getLang().OpenCL)
3113        goto DoneWithTypeQuals;
3114    case tok::kw___private:
3115    case tok::kw___global:
3116    case tok::kw___local:
3117    case tok::kw___constant:
3118    case tok::kw___read_only:
3119    case tok::kw___write_only:
3120    case tok::kw___read_write:
3121      ParseOpenCLQualifiers(DS);
3122      break;
3123
3124    case tok::kw___w64:
3125    case tok::kw___ptr64:
3126    case tok::kw___cdecl:
3127    case tok::kw___stdcall:
3128    case tok::kw___fastcall:
3129    case tok::kw___thiscall:
3130      if (VendorAttributesAllowed) {
3131        ParseMicrosoftTypeAttributes(DS.getAttributes());
3132        continue;
3133      }
3134      goto DoneWithTypeQuals;
3135    case tok::kw___pascal:
3136      if (VendorAttributesAllowed) {
3137        ParseBorlandTypeAttributes(DS.getAttributes());
3138        continue;
3139      }
3140      goto DoneWithTypeQuals;
3141    case tok::kw___attribute:
3142      if (VendorAttributesAllowed) {
3143        ParseGNUAttributes(DS.getAttributes());
3144        continue; // do *not* consume the next token!
3145      }
3146      // otherwise, FALL THROUGH!
3147    default:
3148      DoneWithTypeQuals:
3149      // If this is not a type-qualifier token, we're done reading type
3150      // qualifiers.  First verify that DeclSpec's are consistent.
3151      DS.Finish(Diags, PP);
3152      if (EndLoc.isValid())
3153        DS.SetRangeEnd(EndLoc);
3154      return;
3155    }
3156
3157    // If the specifier combination wasn't legal, issue a diagnostic.
3158    if (isInvalid) {
3159      assert(PrevSpec && "Method did not return previous specifier!");
3160      Diag(Tok, DiagID) << PrevSpec;
3161    }
3162    EndLoc = ConsumeToken();
3163  }
3164}
3165
3166
3167/// ParseDeclarator - Parse and verify a newly-initialized declarator.
3168///
3169void Parser::ParseDeclarator(Declarator &D) {
3170  /// This implements the 'declarator' production in the C grammar, then checks
3171  /// for well-formedness and issues diagnostics.
3172  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3173}
3174
3175/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
3176/// is parsed by the function passed to it. Pass null, and the direct-declarator
3177/// isn't parsed at all, making this function effectively parse the C++
3178/// ptr-operator production.
3179///
3180///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
3181/// [C]     pointer[opt] direct-declarator
3182/// [C++]   direct-declarator
3183/// [C++]   ptr-operator declarator
3184///
3185///       pointer: [C99 6.7.5]
3186///         '*' type-qualifier-list[opt]
3187///         '*' type-qualifier-list[opt] pointer
3188///
3189///       ptr-operator:
3190///         '*' cv-qualifier-seq[opt]
3191///         '&'
3192/// [C++0x] '&&'
3193/// [GNU]   '&' restrict[opt] attributes[opt]
3194/// [GNU?]  '&&' restrict[opt] attributes[opt]
3195///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
3196void Parser::ParseDeclaratorInternal(Declarator &D,
3197                                     DirectDeclParseFunction DirectDeclParser) {
3198  if (Diags.hasAllExtensionsSilenced())
3199    D.setExtension();
3200
3201  // C++ member pointers start with a '::' or a nested-name.
3202  // Member pointers get special handling, since there's no place for the
3203  // scope spec in the generic path below.
3204  if (getLang().CPlusPlus &&
3205      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
3206       Tok.is(tok::annot_cxxscope))) {
3207    CXXScopeSpec SS;
3208    ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true); // ignore fail
3209
3210    if (SS.isNotEmpty()) {
3211      if (Tok.isNot(tok::star)) {
3212        // The scope spec really belongs to the direct-declarator.
3213        D.getCXXScopeSpec() = SS;
3214        if (DirectDeclParser)
3215          (this->*DirectDeclParser)(D);
3216        return;
3217      }
3218
3219      SourceLocation Loc = ConsumeToken();
3220      D.SetRangeEnd(Loc);
3221      DeclSpec DS(AttrFactory);
3222      ParseTypeQualifierListOpt(DS);
3223      D.ExtendWithDeclSpec(DS);
3224
3225      // Recurse to parse whatever is left.
3226      ParseDeclaratorInternal(D, DirectDeclParser);
3227
3228      // Sema will have to catch (syntactically invalid) pointers into global
3229      // scope. It has to catch pointers into namespace scope anyway.
3230      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
3231                                                      Loc),
3232                    DS.getAttributes(),
3233                    /* Don't replace range end. */SourceLocation());
3234      return;
3235    }
3236  }
3237
3238  tok::TokenKind Kind = Tok.getKind();
3239  // Not a pointer, C++ reference, or block.
3240  if (Kind != tok::star && Kind != tok::caret &&
3241      (Kind != tok::amp || !getLang().CPlusPlus) &&
3242      // We parse rvalue refs in C++03, because otherwise the errors are scary.
3243      (Kind != tok::ampamp || !getLang().CPlusPlus)) {
3244    if (DirectDeclParser)
3245      (this->*DirectDeclParser)(D);
3246    return;
3247  }
3248
3249  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
3250  // '&&' -> rvalue reference
3251  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
3252  D.SetRangeEnd(Loc);
3253
3254  if (Kind == tok::star || Kind == tok::caret) {
3255    // Is a pointer.
3256    DeclSpec DS(AttrFactory);
3257
3258    ParseTypeQualifierListOpt(DS);
3259    D.ExtendWithDeclSpec(DS);
3260
3261    // Recursively parse the declarator.
3262    ParseDeclaratorInternal(D, DirectDeclParser);
3263    if (Kind == tok::star)
3264      // Remember that we parsed a pointer type, and remember the type-quals.
3265      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
3266                                                DS.getConstSpecLoc(),
3267                                                DS.getVolatileSpecLoc(),
3268                                                DS.getRestrictSpecLoc()),
3269                    DS.getAttributes(),
3270                    SourceLocation());
3271    else
3272      // Remember that we parsed a Block type, and remember the type-quals.
3273      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
3274                                                     Loc),
3275                    DS.getAttributes(),
3276                    SourceLocation());
3277  } else {
3278    // Is a reference
3279    DeclSpec DS(AttrFactory);
3280
3281    // Complain about rvalue references in C++03, but then go on and build
3282    // the declarator.
3283    if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
3284      Diag(Loc, diag::ext_rvalue_reference);
3285
3286    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
3287    // cv-qualifiers are introduced through the use of a typedef or of a
3288    // template type argument, in which case the cv-qualifiers are ignored.
3289    //
3290    // [GNU] Retricted references are allowed.
3291    // [GNU] Attributes on references are allowed.
3292    // [C++0x] Attributes on references are not allowed.
3293    ParseTypeQualifierListOpt(DS, true, false);
3294    D.ExtendWithDeclSpec(DS);
3295
3296    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
3297      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3298        Diag(DS.getConstSpecLoc(),
3299             diag::err_invalid_reference_qualifier_application) << "const";
3300      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3301        Diag(DS.getVolatileSpecLoc(),
3302             diag::err_invalid_reference_qualifier_application) << "volatile";
3303    }
3304
3305    // Recursively parse the declarator.
3306    ParseDeclaratorInternal(D, DirectDeclParser);
3307
3308    if (D.getNumTypeObjects() > 0) {
3309      // C++ [dcl.ref]p4: There shall be no references to references.
3310      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
3311      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
3312        if (const IdentifierInfo *II = D.getIdentifier())
3313          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3314           << II;
3315        else
3316          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3317            << "type name";
3318
3319        // Once we've complained about the reference-to-reference, we
3320        // can go ahead and build the (technically ill-formed)
3321        // declarator: reference collapsing will take care of it.
3322      }
3323    }
3324
3325    // Remember that we parsed a reference type. It doesn't have type-quals.
3326    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
3327                                                Kind == tok::amp),
3328                  DS.getAttributes(),
3329                  SourceLocation());
3330  }
3331}
3332
3333/// ParseDirectDeclarator
3334///       direct-declarator: [C99 6.7.5]
3335/// [C99]   identifier
3336///         '(' declarator ')'
3337/// [GNU]   '(' attributes declarator ')'
3338/// [C90]   direct-declarator '[' constant-expression[opt] ']'
3339/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3340/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3341/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3342/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
3343///         direct-declarator '(' parameter-type-list ')'
3344///         direct-declarator '(' identifier-list[opt] ')'
3345/// [GNU]   direct-declarator '(' parameter-forward-declarations
3346///                    parameter-type-list[opt] ')'
3347/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
3348///                    cv-qualifier-seq[opt] exception-specification[opt]
3349/// [C++]   declarator-id
3350///
3351///       declarator-id: [C++ 8]
3352///         '...'[opt] id-expression
3353///         '::'[opt] nested-name-specifier[opt] type-name
3354///
3355///       id-expression: [C++ 5.1]
3356///         unqualified-id
3357///         qualified-id
3358///
3359///       unqualified-id: [C++ 5.1]
3360///         identifier
3361///         operator-function-id
3362///         conversion-function-id
3363///          '~' class-name
3364///         template-id
3365///
3366void Parser::ParseDirectDeclarator(Declarator &D) {
3367  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
3368
3369  if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
3370    // ParseDeclaratorInternal might already have parsed the scope.
3371    if (D.getCXXScopeSpec().isEmpty()) {
3372      ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), true);
3373    }
3374
3375    if (D.getCXXScopeSpec().isValid()) {
3376      if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3377        // Change the declaration context for name lookup, until this function
3378        // is exited (and the declarator has been parsed).
3379        DeclScopeObj.EnterDeclaratorScope();
3380    }
3381
3382    // C++0x [dcl.fct]p14:
3383    //   There is a syntactic ambiguity when an ellipsis occurs at the end
3384    //   of a parameter-declaration-clause without a preceding comma. In
3385    //   this case, the ellipsis is parsed as part of the
3386    //   abstract-declarator if the type of the parameter names a template
3387    //   parameter pack that has not been expanded; otherwise, it is parsed
3388    //   as part of the parameter-declaration-clause.
3389    if (Tok.is(tok::ellipsis) &&
3390        !((D.getContext() == Declarator::PrototypeContext ||
3391           D.getContext() == Declarator::BlockLiteralContext) &&
3392          NextToken().is(tok::r_paren) &&
3393          !Actions.containsUnexpandedParameterPacks(D)))
3394      D.setEllipsisLoc(ConsumeToken());
3395
3396    if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
3397        Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
3398      // We found something that indicates the start of an unqualified-id.
3399      // Parse that unqualified-id.
3400      bool AllowConstructorName;
3401      if (D.getDeclSpec().hasTypeSpecifier())
3402        AllowConstructorName = false;
3403      else if (D.getCXXScopeSpec().isSet())
3404        AllowConstructorName =
3405          (D.getContext() == Declarator::FileContext ||
3406           (D.getContext() == Declarator::MemberContext &&
3407            D.getDeclSpec().isFriendSpecified()));
3408      else
3409        AllowConstructorName = (D.getContext() == Declarator::MemberContext);
3410
3411      if (ParseUnqualifiedId(D.getCXXScopeSpec(),
3412                             /*EnteringContext=*/true,
3413                             /*AllowDestructorName=*/true,
3414                             AllowConstructorName,
3415                             ParsedType(),
3416                             D.getName()) ||
3417          // Once we're past the identifier, if the scope was bad, mark the
3418          // whole declarator bad.
3419          D.getCXXScopeSpec().isInvalid()) {
3420        D.SetIdentifier(0, Tok.getLocation());
3421        D.setInvalidType(true);
3422      } else {
3423        // Parsed the unqualified-id; update range information and move along.
3424        if (D.getSourceRange().getBegin().isInvalid())
3425          D.SetRangeBegin(D.getName().getSourceRange().getBegin());
3426        D.SetRangeEnd(D.getName().getSourceRange().getEnd());
3427      }
3428      goto PastIdentifier;
3429    }
3430  } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
3431    assert(!getLang().CPlusPlus &&
3432           "There's a C++-specific check for tok::identifier above");
3433    assert(Tok.getIdentifierInfo() && "Not an identifier?");
3434    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
3435    ConsumeToken();
3436    goto PastIdentifier;
3437  }
3438
3439  if (Tok.is(tok::l_paren)) {
3440    // direct-declarator: '(' declarator ')'
3441    // direct-declarator: '(' attributes declarator ')'
3442    // Example: 'char (*X)'   or 'int (*XX)(void)'
3443    ParseParenDeclarator(D);
3444
3445    // If the declarator was parenthesized, we entered the declarator
3446    // scope when parsing the parenthesized declarator, then exited
3447    // the scope already. Re-enter the scope, if we need to.
3448    if (D.getCXXScopeSpec().isSet()) {
3449      // If there was an error parsing parenthesized declarator, declarator
3450      // scope may have been enterred before. Don't do it again.
3451      if (!D.isInvalidType() &&
3452          Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3453        // Change the declaration context for name lookup, until this function
3454        // is exited (and the declarator has been parsed).
3455        DeclScopeObj.EnterDeclaratorScope();
3456    }
3457  } else if (D.mayOmitIdentifier()) {
3458    // This could be something simple like "int" (in which case the declarator
3459    // portion is empty), if an abstract-declarator is allowed.
3460    D.SetIdentifier(0, Tok.getLocation());
3461  } else {
3462    if (D.getContext() == Declarator::MemberContext)
3463      Diag(Tok, diag::err_expected_member_name_or_semi)
3464        << D.getDeclSpec().getSourceRange();
3465    else if (getLang().CPlusPlus)
3466      Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
3467    else
3468      Diag(Tok, diag::err_expected_ident_lparen);
3469    D.SetIdentifier(0, Tok.getLocation());
3470    D.setInvalidType(true);
3471  }
3472
3473 PastIdentifier:
3474  assert(D.isPastIdentifier() &&
3475         "Haven't past the location of the identifier yet?");
3476
3477  // Don't parse attributes unless we have an identifier.
3478  if (D.getIdentifier())
3479    MaybeParseCXX0XAttributes(D);
3480
3481  while (1) {
3482    if (Tok.is(tok::l_paren)) {
3483      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
3484      // In such a case, check if we actually have a function declarator; if it
3485      // is not, the declarator has been fully parsed.
3486      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
3487        // When not in file scope, warn for ambiguous function declarators, just
3488        // in case the author intended it as a variable definition.
3489        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
3490        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
3491          break;
3492      }
3493      ParsedAttributes attrs(AttrFactory);
3494      ParseFunctionDeclarator(ConsumeParen(), D, attrs);
3495    } else if (Tok.is(tok::l_square)) {
3496      ParseBracketDeclarator(D);
3497    } else {
3498      break;
3499    }
3500  }
3501}
3502
3503/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
3504/// only called before the identifier, so these are most likely just grouping
3505/// parens for precedence.  If we find that these are actually function
3506/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
3507///
3508///       direct-declarator:
3509///         '(' declarator ')'
3510/// [GNU]   '(' attributes declarator ')'
3511///         direct-declarator '(' parameter-type-list ')'
3512///         direct-declarator '(' identifier-list[opt] ')'
3513/// [GNU]   direct-declarator '(' parameter-forward-declarations
3514///                    parameter-type-list[opt] ')'
3515///
3516void Parser::ParseParenDeclarator(Declarator &D) {
3517  SourceLocation StartLoc = ConsumeParen();
3518  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
3519
3520  // Eat any attributes before we look at whether this is a grouping or function
3521  // declarator paren.  If this is a grouping paren, the attribute applies to
3522  // the type being built up, for example:
3523  //     int (__attribute__(()) *x)(long y)
3524  // If this ends up not being a grouping paren, the attribute applies to the
3525  // first argument, for example:
3526  //     int (__attribute__(()) int x)
3527  // In either case, we need to eat any attributes to be able to determine what
3528  // sort of paren this is.
3529  //
3530  ParsedAttributes attrs(AttrFactory);
3531  bool RequiresArg = false;
3532  if (Tok.is(tok::kw___attribute)) {
3533    ParseGNUAttributes(attrs);
3534
3535    // We require that the argument list (if this is a non-grouping paren) be
3536    // present even if the attribute list was empty.
3537    RequiresArg = true;
3538  }
3539  // Eat any Microsoft extensions.
3540  if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
3541       Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
3542       Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64)) {
3543    ParseMicrosoftTypeAttributes(attrs);
3544  }
3545  // Eat any Borland extensions.
3546  if  (Tok.is(tok::kw___pascal))
3547    ParseBorlandTypeAttributes(attrs);
3548
3549  // If we haven't past the identifier yet (or where the identifier would be
3550  // stored, if this is an abstract declarator), then this is probably just
3551  // grouping parens. However, if this could be an abstract-declarator, then
3552  // this could also be the start of function arguments (consider 'void()').
3553  bool isGrouping;
3554
3555  if (!D.mayOmitIdentifier()) {
3556    // If this can't be an abstract-declarator, this *must* be a grouping
3557    // paren, because we haven't seen the identifier yet.
3558    isGrouping = true;
3559  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
3560             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
3561             isDeclarationSpecifier()) {       // 'int(int)' is a function.
3562    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
3563    // considered to be a type, not a K&R identifier-list.
3564    isGrouping = false;
3565  } else {
3566    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
3567    isGrouping = true;
3568  }
3569
3570  // If this is a grouping paren, handle:
3571  // direct-declarator: '(' declarator ')'
3572  // direct-declarator: '(' attributes declarator ')'
3573  if (isGrouping) {
3574    bool hadGroupingParens = D.hasGroupingParens();
3575    D.setGroupingParens(true);
3576
3577    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3578    // Match the ')'.
3579    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, StartLoc);
3580    D.AddTypeInfo(DeclaratorChunk::getParen(StartLoc, EndLoc),
3581                  attrs, EndLoc);
3582
3583    D.setGroupingParens(hadGroupingParens);
3584    return;
3585  }
3586
3587  // Okay, if this wasn't a grouping paren, it must be the start of a function
3588  // argument list.  Recognize that this declarator will never have an
3589  // identifier (and remember where it would have been), then call into
3590  // ParseFunctionDeclarator to handle of argument list.
3591  D.SetIdentifier(0, Tok.getLocation());
3592
3593  ParseFunctionDeclarator(StartLoc, D, attrs, RequiresArg);
3594}
3595
3596/// ParseFunctionDeclarator - We are after the identifier and have parsed the
3597/// declarator D up to a paren, which indicates that we are parsing function
3598/// arguments.
3599///
3600/// If AttrList is non-null, then the caller parsed those arguments immediately
3601/// after the open paren - they should be considered to be the first argument of
3602/// a parameter.  If RequiresArg is true, then the first argument of the
3603/// function is required to be present and required to not be an identifier
3604/// list.
3605///
3606/// This method also handles this portion of the grammar:
3607///       parameter-type-list: [C99 6.7.5]
3608///         parameter-list
3609///         parameter-list ',' '...'
3610/// [C++]   parameter-list '...'
3611///
3612///       parameter-list: [C99 6.7.5]
3613///         parameter-declaration
3614///         parameter-list ',' parameter-declaration
3615///
3616///       parameter-declaration: [C99 6.7.5]
3617///         declaration-specifiers declarator
3618/// [C++]   declaration-specifiers declarator '=' assignment-expression
3619/// [GNU]   declaration-specifiers declarator attributes
3620///         declaration-specifiers abstract-declarator[opt]
3621/// [C++]   declaration-specifiers abstract-declarator[opt]
3622///           '=' assignment-expression
3623/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
3624///
3625/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]",
3626/// C++0x "ref-qualifier[opt]" and "exception-specification[opt]".
3627///
3628/// [C++0x] exception-specification:
3629///           dynamic-exception-specification
3630///           noexcept-specification
3631///
3632void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
3633                                     ParsedAttributes &attrs,
3634                                     bool RequiresArg) {
3635  // lparen is already consumed!
3636  assert(D.isPastIdentifier() && "Should not call before identifier!");
3637
3638  ParsedType TrailingReturnType;
3639
3640  // This parameter list may be empty.
3641  if (Tok.is(tok::r_paren)) {
3642    if (RequiresArg)
3643      Diag(Tok, diag::err_argument_required_after_attribute);
3644
3645    SourceLocation EndLoc = ConsumeParen();  // Eat the closing ')'.
3646
3647    // cv-qualifier-seq[opt].
3648    DeclSpec DS(AttrFactory);
3649    SourceLocation RefQualifierLoc;
3650    bool RefQualifierIsLValueRef = true;
3651    ExceptionSpecificationType ESpecType = EST_None;
3652    SourceRange ESpecRange;
3653    llvm::SmallVector<ParsedType, 2> DynamicExceptions;
3654    llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
3655    ExprResult NoexceptExpr;
3656    if (getLang().CPlusPlus) {
3657      MaybeParseCXX0XAttributes(attrs);
3658
3659      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3660      if (!DS.getSourceRange().getEnd().isInvalid())
3661        EndLoc = DS.getSourceRange().getEnd();
3662
3663      // Parse ref-qualifier[opt]
3664      if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
3665        if (!getLang().CPlusPlus0x)
3666          Diag(Tok, diag::ext_ref_qualifier);
3667
3668        RefQualifierIsLValueRef = Tok.is(tok::amp);
3669        RefQualifierLoc = ConsumeToken();
3670        EndLoc = RefQualifierLoc;
3671      }
3672
3673      // Parse exception-specification[opt].
3674      ESpecType = MaybeParseExceptionSpecification(ESpecRange,
3675                                                   DynamicExceptions,
3676                                                   DynamicExceptionRanges,
3677                                                   NoexceptExpr);
3678      if (ESpecType != EST_None)
3679        EndLoc = ESpecRange.getEnd();
3680
3681      // Parse trailing-return-type.
3682      if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
3683        TrailingReturnType = ParseTrailingReturnType().get();
3684      }
3685    }
3686
3687    // Remember that we parsed a function type, and remember the attributes.
3688    // int() -> no prototype, no '...'.
3689    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
3690                                               /*variadic*/ false,
3691                                               SourceLocation(),
3692                                               /*arglist*/ 0, 0,
3693                                               DS.getTypeQualifiers(),
3694                                               RefQualifierIsLValueRef,
3695                                               RefQualifierLoc,
3696                                               ESpecType, ESpecRange.getBegin(),
3697                                               DynamicExceptions.data(),
3698                                               DynamicExceptionRanges.data(),
3699                                               DynamicExceptions.size(),
3700                                               NoexceptExpr.isUsable() ?
3701                                                 NoexceptExpr.get() : 0,
3702                                               LParenLoc, EndLoc, D,
3703                                               TrailingReturnType),
3704                  attrs, EndLoc);
3705    return;
3706  }
3707
3708  // Alternatively, this parameter list may be an identifier list form for a
3709  // K&R-style function:  void foo(a,b,c)
3710  if (!getLang().CPlusPlus && Tok.is(tok::identifier)
3711      && !TryAltiVecVectorToken()) {
3712    if (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) {
3713      // K&R identifier lists can't have typedefs as identifiers, per
3714      // C99 6.7.5.3p11.
3715      if (RequiresArg)
3716        Diag(Tok, diag::err_argument_required_after_attribute);
3717
3718      // Identifier list.  Note that '(' identifier-list ')' is only allowed for
3719      // normal declarators, not for abstract-declarators.  Get the first
3720      // identifier.
3721      Token FirstTok = Tok;
3722      ConsumeToken();  // eat the first identifier.
3723
3724      // Identifier lists follow a really simple grammar: the identifiers can
3725      // be followed *only* by a ", moreidentifiers" or ")".  However, K&R
3726      // identifier lists are really rare in the brave new modern world, and it
3727      // is very common for someone to typo a type in a non-k&r style list.  If
3728      // we are presented with something like: "void foo(intptr x, float y)",
3729      // we don't want to start parsing the function declarator as though it is
3730      // a K&R style declarator just because intptr is an invalid type.
3731      //
3732      // To handle this, we check to see if the token after the first identifier
3733      // is a "," or ")".  Only if so, do we parse it as an identifier list.
3734      if (Tok.is(tok::comma) || Tok.is(tok::r_paren))
3735        return ParseFunctionDeclaratorIdentifierList(LParenLoc,
3736                                                   FirstTok.getIdentifierInfo(),
3737                                                     FirstTok.getLocation(), D);
3738
3739      // If we get here, the code is invalid.  Push the first identifier back
3740      // into the token stream and parse the first argument as an (invalid)
3741      // normal argument declarator.
3742      PP.EnterToken(Tok);
3743      Tok = FirstTok;
3744    }
3745  }
3746
3747  // Finally, a normal, non-empty parameter type list.
3748
3749  // Build up an array of information about the parsed arguments.
3750  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3751
3752  // Enter function-declaration scope, limiting any declarators to the
3753  // function prototype scope, including parameter declarators.
3754  ParseScope PrototypeScope(this,
3755                            Scope::FunctionPrototypeScope|Scope::DeclScope);
3756
3757  bool IsVariadic = false;
3758  SourceLocation EllipsisLoc;
3759  while (1) {
3760    if (Tok.is(tok::ellipsis)) {
3761      IsVariadic = true;
3762      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
3763      break;
3764    }
3765
3766    // Parse the declaration-specifiers.
3767    // Just use the ParsingDeclaration "scope" of the declarator.
3768    DeclSpec DS(AttrFactory);
3769
3770    // Skip any Microsoft attributes before a param.
3771    if (getLang().Microsoft && Tok.is(tok::l_square))
3772      ParseMicrosoftAttributes(DS.getAttributes());
3773
3774    SourceLocation DSStart = Tok.getLocation();
3775
3776    // If the caller parsed attributes for the first argument, add them now.
3777    // Take them so that we only apply the attributes to the first parameter.
3778    DS.takeAttributesFrom(attrs);
3779
3780    ParseDeclarationSpecifiers(DS);
3781
3782    // Parse the declarator.  This is "PrototypeContext", because we must
3783    // accept either 'declarator' or 'abstract-declarator' here.
3784    Declarator ParmDecl(DS, Declarator::PrototypeContext);
3785    ParseDeclarator(ParmDecl);
3786
3787    // Parse GNU attributes, if present.
3788    MaybeParseGNUAttributes(ParmDecl);
3789
3790    // Remember this parsed parameter in ParamInfo.
3791    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
3792
3793    // DefArgToks is used when the parsing of default arguments needs
3794    // to be delayed.
3795    CachedTokens *DefArgToks = 0;
3796
3797    // If no parameter was specified, verify that *something* was specified,
3798    // otherwise we have a missing type and identifier.
3799    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
3800        ParmDecl.getNumTypeObjects() == 0) {
3801      // Completely missing, emit error.
3802      Diag(DSStart, diag::err_missing_param);
3803    } else {
3804      // Otherwise, we have something.  Add it and let semantic analysis try
3805      // to grok it and add the result to the ParamInfo we are building.
3806
3807      // Inform the actions module about the parameter declarator, so it gets
3808      // added to the current scope.
3809      Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
3810
3811      // Parse the default argument, if any. We parse the default
3812      // arguments in all dialects; the semantic analysis in
3813      // ActOnParamDefaultArgument will reject the default argument in
3814      // C.
3815      if (Tok.is(tok::equal)) {
3816        SourceLocation EqualLoc = Tok.getLocation();
3817
3818        // Parse the default argument
3819        if (D.getContext() == Declarator::MemberContext) {
3820          // If we're inside a class definition, cache the tokens
3821          // corresponding to the default argument. We'll actually parse
3822          // them when we see the end of the class definition.
3823          // FIXME: Templates will require something similar.
3824          // FIXME: Can we use a smart pointer for Toks?
3825          DefArgToks = new CachedTokens;
3826
3827          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
3828                                    /*StopAtSemi=*/true,
3829                                    /*ConsumeFinalToken=*/false)) {
3830            delete DefArgToks;
3831            DefArgToks = 0;
3832            Actions.ActOnParamDefaultArgumentError(Param);
3833          } else {
3834            // Mark the end of the default argument so that we know when to
3835            // stop when we parse it later on.
3836            Token DefArgEnd;
3837            DefArgEnd.startToken();
3838            DefArgEnd.setKind(tok::cxx_defaultarg_end);
3839            DefArgEnd.setLocation(Tok.getLocation());
3840            DefArgToks->push_back(DefArgEnd);
3841            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
3842                                                (*DefArgToks)[1].getLocation());
3843          }
3844        } else {
3845          // Consume the '='.
3846          ConsumeToken();
3847
3848          // The argument isn't actually potentially evaluated unless it is
3849          // used.
3850          EnterExpressionEvaluationContext Eval(Actions,
3851                                              Sema::PotentiallyEvaluatedIfUsed);
3852
3853          ExprResult DefArgResult(ParseAssignmentExpression());
3854          if (DefArgResult.isInvalid()) {
3855            Actions.ActOnParamDefaultArgumentError(Param);
3856            SkipUntil(tok::comma, tok::r_paren, true, true);
3857          } else {
3858            // Inform the actions module about the default argument
3859            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
3860                                              DefArgResult.take());
3861          }
3862        }
3863      }
3864
3865      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3866                                          ParmDecl.getIdentifierLoc(), Param,
3867                                          DefArgToks));
3868    }
3869
3870    // If the next token is a comma, consume it and keep reading arguments.
3871    if (Tok.isNot(tok::comma)) {
3872      if (Tok.is(tok::ellipsis)) {
3873        IsVariadic = true;
3874        EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
3875
3876        if (!getLang().CPlusPlus) {
3877          // We have ellipsis without a preceding ',', which is ill-formed
3878          // in C. Complain and provide the fix.
3879          Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
3880            << FixItHint::CreateInsertion(EllipsisLoc, ", ");
3881        }
3882      }
3883
3884      break;
3885    }
3886
3887    // Consume the comma.
3888    ConsumeToken();
3889  }
3890
3891  // If we have the closing ')', eat it.
3892  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3893
3894  DeclSpec DS(AttrFactory);
3895  SourceLocation RefQualifierLoc;
3896  bool RefQualifierIsLValueRef = true;
3897  ExceptionSpecificationType ESpecType = EST_None;
3898  SourceRange ESpecRange;
3899  llvm::SmallVector<ParsedType, 2> DynamicExceptions;
3900  llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
3901  ExprResult NoexceptExpr;
3902
3903  if (getLang().CPlusPlus) {
3904    MaybeParseCXX0XAttributes(attrs);
3905
3906    // Parse cv-qualifier-seq[opt].
3907    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3908      if (!DS.getSourceRange().getEnd().isInvalid())
3909        EndLoc = DS.getSourceRange().getEnd();
3910
3911    // Parse ref-qualifier[opt]
3912    if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
3913      if (!getLang().CPlusPlus0x)
3914        Diag(Tok, diag::ext_ref_qualifier);
3915
3916      RefQualifierIsLValueRef = Tok.is(tok::amp);
3917      RefQualifierLoc = ConsumeToken();
3918      EndLoc = RefQualifierLoc;
3919    }
3920
3921    // FIXME: We should leave the prototype scope before parsing the exception
3922    // specification, and then reenter it when parsing the trailing return type.
3923    // FIXMEFIXME: Why? That wouldn't be right for the noexcept clause.
3924
3925    // Parse exception-specification[opt].
3926    ESpecType = MaybeParseExceptionSpecification(ESpecRange,
3927                                                 DynamicExceptions,
3928                                                 DynamicExceptionRanges,
3929                                                 NoexceptExpr);
3930    if (ESpecType != EST_None)
3931      EndLoc = ESpecRange.getEnd();
3932
3933    // Parse trailing-return-type.
3934    if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
3935      TrailingReturnType = ParseTrailingReturnType().get();
3936    }
3937  }
3938
3939  // Leave prototype scope.
3940  PrototypeScope.Exit();
3941
3942  // Remember that we parsed a function type, and remember the attributes.
3943  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
3944                                             EllipsisLoc,
3945                                             ParamInfo.data(), ParamInfo.size(),
3946                                             DS.getTypeQualifiers(),
3947                                             RefQualifierIsLValueRef,
3948                                             RefQualifierLoc,
3949                                             ESpecType, ESpecRange.getBegin(),
3950                                             DynamicExceptions.data(),
3951                                             DynamicExceptionRanges.data(),
3952                                             DynamicExceptions.size(),
3953                                             NoexceptExpr.isUsable() ?
3954                                               NoexceptExpr.get() : 0,
3955                                             LParenLoc, EndLoc, D,
3956                                             TrailingReturnType),
3957                attrs, EndLoc);
3958}
3959
3960/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
3961/// we found a K&R-style identifier list instead of a type argument list.  The
3962/// first identifier has already been consumed, and the current token is the
3963/// token right after it.
3964///
3965///       identifier-list: [C99 6.7.5]
3966///         identifier
3967///         identifier-list ',' identifier
3968///
3969void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
3970                                                   IdentifierInfo *FirstIdent,
3971                                                   SourceLocation FirstIdentLoc,
3972                                                   Declarator &D) {
3973  // Build up an array of information about the parsed arguments.
3974  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3975  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
3976
3977  // If there was no identifier specified for the declarator, either we are in
3978  // an abstract-declarator, or we are in a parameter declarator which was found
3979  // to be abstract.  In abstract-declarators, identifier lists are not valid:
3980  // diagnose this.
3981  if (!D.getIdentifier())
3982    Diag(FirstIdentLoc, diag::ext_ident_list_in_param);
3983
3984  // The first identifier was already read, and is known to be the first
3985  // identifier in the list.  Remember this identifier in ParamInfo.
3986  ParamsSoFar.insert(FirstIdent);
3987  ParamInfo.push_back(DeclaratorChunk::ParamInfo(FirstIdent, FirstIdentLoc, 0));
3988
3989  while (Tok.is(tok::comma)) {
3990    // Eat the comma.
3991    ConsumeToken();
3992
3993    // If this isn't an identifier, report the error and skip until ')'.
3994    if (Tok.isNot(tok::identifier)) {
3995      Diag(Tok, diag::err_expected_ident);
3996      SkipUntil(tok::r_paren);
3997      return;
3998    }
3999
4000    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
4001
4002    // Reject 'typedef int y; int test(x, y)', but continue parsing.
4003    if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
4004      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
4005
4006    // Verify that the argument identifier has not already been mentioned.
4007    if (!ParamsSoFar.insert(ParmII)) {
4008      Diag(Tok, diag::err_param_redefinition) << ParmII;
4009    } else {
4010      // Remember this identifier in ParamInfo.
4011      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4012                                                     Tok.getLocation(),
4013                                                     0));
4014    }
4015
4016    // Eat the identifier.
4017    ConsumeToken();
4018  }
4019
4020  // If we have the closing ')', eat it and we're done.
4021  SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
4022
4023  // Remember that we parsed a function type, and remember the attributes.  This
4024  // function type is always a K&R style function type, which is not varargs and
4025  // has no prototype.
4026  ParsedAttributes attrs(AttrFactory);
4027  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
4028                                             SourceLocation(),
4029                                             &ParamInfo[0], ParamInfo.size(),
4030                                             /*TypeQuals*/0,
4031                                             true, SourceLocation(),
4032                                             EST_None, SourceLocation(), 0, 0,
4033                                             0, 0, LParenLoc, RLoc, D),
4034                attrs, RLoc);
4035}
4036
4037/// [C90]   direct-declarator '[' constant-expression[opt] ']'
4038/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4039/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4040/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4041/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
4042void Parser::ParseBracketDeclarator(Declarator &D) {
4043  SourceLocation StartLoc = ConsumeBracket();
4044
4045  // C array syntax has many features, but by-far the most common is [] and [4].
4046  // This code does a fast path to handle some of the most obvious cases.
4047  if (Tok.getKind() == tok::r_square) {
4048    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4049    ParsedAttributes attrs(AttrFactory);
4050    MaybeParseCXX0XAttributes(attrs);
4051
4052    // Remember that we parsed the empty array type.
4053    ExprResult NumElements;
4054    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
4055                                            StartLoc, EndLoc),
4056                  attrs, EndLoc);
4057    return;
4058  } else if (Tok.getKind() == tok::numeric_constant &&
4059             GetLookAheadToken(1).is(tok::r_square)) {
4060    // [4] is very common.  Parse the numeric constant expression.
4061    ExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
4062    ConsumeToken();
4063
4064    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4065    ParsedAttributes attrs(AttrFactory);
4066    MaybeParseCXX0XAttributes(attrs);
4067
4068    // Remember that we parsed a array type, and remember its features.
4069    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
4070                                            ExprRes.release(),
4071                                            StartLoc, EndLoc),
4072                  attrs, EndLoc);
4073    return;
4074  }
4075
4076  // If valid, this location is the position where we read the 'static' keyword.
4077  SourceLocation StaticLoc;
4078  if (Tok.is(tok::kw_static))
4079    StaticLoc = ConsumeToken();
4080
4081  // If there is a type-qualifier-list, read it now.
4082  // Type qualifiers in an array subscript are a C99 feature.
4083  DeclSpec DS(AttrFactory);
4084  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
4085
4086  // If we haven't already read 'static', check to see if there is one after the
4087  // type-qualifier-list.
4088  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
4089    StaticLoc = ConsumeToken();
4090
4091  // Handle "direct-declarator [ type-qual-list[opt] * ]".
4092  bool isStar = false;
4093  ExprResult NumElements;
4094
4095  // Handle the case where we have '[*]' as the array size.  However, a leading
4096  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
4097  // the the token after the star is a ']'.  Since stars in arrays are
4098  // infrequent, use of lookahead is not costly here.
4099  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
4100    ConsumeToken();  // Eat the '*'.
4101
4102    if (StaticLoc.isValid()) {
4103      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
4104      StaticLoc = SourceLocation();  // Drop the static.
4105    }
4106    isStar = true;
4107  } else if (Tok.isNot(tok::r_square)) {
4108    // Note, in C89, this production uses the constant-expr production instead
4109    // of assignment-expr.  The only difference is that assignment-expr allows
4110    // things like '=' and '*='.  Sema rejects these in C89 mode because they
4111    // are not i-c-e's, so we don't need to distinguish between the two here.
4112
4113    // Parse the constant-expression or assignment-expression now (depending
4114    // on dialect).
4115    if (getLang().CPlusPlus)
4116      NumElements = ParseConstantExpression();
4117    else
4118      NumElements = ParseAssignmentExpression();
4119  }
4120
4121  // If there was an error parsing the assignment-expression, recover.
4122  if (NumElements.isInvalid()) {
4123    D.setInvalidType(true);
4124    // If the expression was invalid, skip it.
4125    SkipUntil(tok::r_square);
4126    return;
4127  }
4128
4129  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4130
4131  ParsedAttributes attrs(AttrFactory);
4132  MaybeParseCXX0XAttributes(attrs);
4133
4134  // Remember that we parsed a array type, and remember its features.
4135  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
4136                                          StaticLoc.isValid(), isStar,
4137                                          NumElements.release(),
4138                                          StartLoc, EndLoc),
4139                attrs, EndLoc);
4140}
4141
4142/// [GNU]   typeof-specifier:
4143///           typeof ( expressions )
4144///           typeof ( type-name )
4145/// [GNU/C++] typeof unary-expression
4146///
4147void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
4148  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
4149  Token OpTok = Tok;
4150  SourceLocation StartLoc = ConsumeToken();
4151
4152  const bool hasParens = Tok.is(tok::l_paren);
4153
4154  bool isCastExpr;
4155  ParsedType CastTy;
4156  SourceRange CastRange;
4157  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
4158                                                          CastTy, CastRange);
4159  if (hasParens)
4160    DS.setTypeofParensRange(CastRange);
4161
4162  if (CastRange.getEnd().isInvalid())
4163    // FIXME: Not accurate, the range gets one token more than it should.
4164    DS.SetRangeEnd(Tok.getLocation());
4165  else
4166    DS.SetRangeEnd(CastRange.getEnd());
4167
4168  if (isCastExpr) {
4169    if (!CastTy) {
4170      DS.SetTypeSpecError();
4171      return;
4172    }
4173
4174    const char *PrevSpec = 0;
4175    unsigned DiagID;
4176    // Check for duplicate type specifiers (e.g. "int typeof(int)").
4177    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
4178                           DiagID, CastTy))
4179      Diag(StartLoc, DiagID) << PrevSpec;
4180    return;
4181  }
4182
4183  // If we get here, the operand to the typeof was an expresion.
4184  if (Operand.isInvalid()) {
4185    DS.SetTypeSpecError();
4186    return;
4187  }
4188
4189  const char *PrevSpec = 0;
4190  unsigned DiagID;
4191  // Check for duplicate type specifiers (e.g. "int typeof(int)").
4192  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
4193                         DiagID, Operand.get()))
4194    Diag(StartLoc, DiagID) << PrevSpec;
4195}
4196
4197
4198/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
4199/// from TryAltiVecVectorToken.
4200bool Parser::TryAltiVecVectorTokenOutOfLine() {
4201  Token Next = NextToken();
4202  switch (Next.getKind()) {
4203  default: return false;
4204  case tok::kw_short:
4205  case tok::kw_long:
4206  case tok::kw_signed:
4207  case tok::kw_unsigned:
4208  case tok::kw_void:
4209  case tok::kw_char:
4210  case tok::kw_int:
4211  case tok::kw_float:
4212  case tok::kw_double:
4213  case tok::kw_bool:
4214  case tok::kw___pixel:
4215    Tok.setKind(tok::kw___vector);
4216    return true;
4217  case tok::identifier:
4218    if (Next.getIdentifierInfo() == Ident_pixel) {
4219      Tok.setKind(tok::kw___vector);
4220      return true;
4221    }
4222    return false;
4223  }
4224}
4225
4226bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
4227                                      const char *&PrevSpec, unsigned &DiagID,
4228                                      bool &isInvalid) {
4229  if (Tok.getIdentifierInfo() == Ident_vector) {
4230    Token Next = NextToken();
4231    switch (Next.getKind()) {
4232    case tok::kw_short:
4233    case tok::kw_long:
4234    case tok::kw_signed:
4235    case tok::kw_unsigned:
4236    case tok::kw_void:
4237    case tok::kw_char:
4238    case tok::kw_int:
4239    case tok::kw_float:
4240    case tok::kw_double:
4241    case tok::kw_bool:
4242    case tok::kw___pixel:
4243      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4244      return true;
4245    case tok::identifier:
4246      if (Next.getIdentifierInfo() == Ident_pixel) {
4247        isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4248        return true;
4249      }
4250      break;
4251    default:
4252      break;
4253    }
4254  } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
4255             DS.isTypeAltiVecVector()) {
4256    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
4257    return true;
4258  }
4259  return false;
4260}
4261