ParseDecl.cpp revision bfad9150bfa894195a43c5f487117672a449f90f
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 {
970      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
971        EnterScope(0);
972        Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
973      }
974
975      if (Tok.is(tok::code_completion)) {
976        Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
977        ConsumeCodeCompletionToken();
978        SkipUntil(tok::comma, true, true);
979        return ThisDecl;
980      }
981
982      ExprResult Init(ParseInitializer());
983
984      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
985        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
986        ExitScope();
987      }
988
989      if (Init.isInvalid()) {
990        SkipUntil(tok::comma, true, true);
991        Actions.ActOnInitializerError(ThisDecl);
992      } else
993        Actions.AddInitializerToDecl(ThisDecl, Init.take(),
994                                     /*DirectInit=*/false, TypeContainsAuto);
995    }
996  } else if (Tok.is(tok::l_paren)) {
997    // Parse C++ direct initializer: '(' expression-list ')'
998    SourceLocation LParenLoc = ConsumeParen();
999    ExprVector Exprs(Actions);
1000    CommaLocsTy CommaLocs;
1001
1002    if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1003      EnterScope(0);
1004      Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
1005    }
1006
1007    if (ParseExpressionList(Exprs, CommaLocs)) {
1008      SkipUntil(tok::r_paren);
1009
1010      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1011        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1012        ExitScope();
1013      }
1014    } else {
1015      // Match the ')'.
1016      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1017
1018      assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
1019             "Unexpected number of commas!");
1020
1021      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
1022        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
1023        ExitScope();
1024      }
1025
1026      Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc,
1027                                            move_arg(Exprs),
1028                                            RParenLoc,
1029                                            TypeContainsAuto);
1030    }
1031  } else {
1032    Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
1033  }
1034
1035  Actions.FinalizeDeclaration(ThisDecl);
1036
1037  return ThisDecl;
1038}
1039
1040/// ParseSpecifierQualifierList
1041///        specifier-qualifier-list:
1042///          type-specifier specifier-qualifier-list[opt]
1043///          type-qualifier specifier-qualifier-list[opt]
1044/// [GNU]    attributes     specifier-qualifier-list[opt]
1045///
1046void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
1047  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
1048  /// parse declaration-specifiers and complain about extra stuff.
1049  ParseDeclarationSpecifiers(DS);
1050
1051  // Validate declspec for type-name.
1052  unsigned Specs = DS.getParsedSpecifiers();
1053  if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1054      !DS.hasAttributes())
1055    Diag(Tok, diag::err_typename_requires_specqual);
1056
1057  // Issue diagnostic and remove storage class if present.
1058  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1059    if (DS.getStorageClassSpecLoc().isValid())
1060      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1061    else
1062      Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
1063    DS.ClearStorageClassSpecs();
1064  }
1065
1066  // Issue diagnostic and remove function specfier if present.
1067  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
1068    if (DS.isInlineSpecified())
1069      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
1070    if (DS.isVirtualSpecified())
1071      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
1072    if (DS.isExplicitSpecified())
1073      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
1074    DS.ClearFunctionSpecs();
1075  }
1076}
1077
1078/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
1079/// specified token is valid after the identifier in a declarator which
1080/// immediately follows the declspec.  For example, these things are valid:
1081///
1082///      int x   [             4];         // direct-declarator
1083///      int x   (             int y);     // direct-declarator
1084///  int(int x   )                         // direct-declarator
1085///      int x   ;                         // simple-declaration
1086///      int x   =             17;         // init-declarator-list
1087///      int x   ,             y;          // init-declarator-list
1088///      int x   __asm__       ("foo");    // init-declarator-list
1089///      int x   :             4;          // struct-declarator
1090///      int x   {             5};         // C++'0x unified initializers
1091///
1092/// This is not, because 'x' does not immediately follow the declspec (though
1093/// ')' happens to be valid anyway).
1094///    int (x)
1095///
1096static bool isValidAfterIdentifierInDeclarator(const Token &T) {
1097  return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
1098         T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
1099         T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
1100}
1101
1102
1103/// ParseImplicitInt - This method is called when we have an non-typename
1104/// identifier in a declspec (which normally terminates the decl spec) when
1105/// the declspec has no type specifier.  In this case, the declspec is either
1106/// malformed or is "implicit int" (in K&R and C89).
1107///
1108/// This method handles diagnosing this prettily and returns false if the
1109/// declspec is done being processed.  If it recovers and thinks there may be
1110/// other pieces of declspec after it, it returns true.
1111///
1112bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1113                              const ParsedTemplateInfo &TemplateInfo,
1114                              AccessSpecifier AS) {
1115  assert(Tok.is(tok::identifier) && "should have identifier");
1116
1117  SourceLocation Loc = Tok.getLocation();
1118  // If we see an identifier that is not a type name, we normally would
1119  // parse it as the identifer being declared.  However, when a typename
1120  // is typo'd or the definition is not included, this will incorrectly
1121  // parse the typename as the identifier name and fall over misparsing
1122  // later parts of the diagnostic.
1123  //
1124  // As such, we try to do some look-ahead in cases where this would
1125  // otherwise be an "implicit-int" case to see if this is invalid.  For
1126  // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
1127  // an identifier with implicit int, we'd get a parse error because the
1128  // next token is obviously invalid for a type.  Parse these as a case
1129  // with an invalid type specifier.
1130  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
1131
1132  // Since we know that this either implicit int (which is rare) or an
1133  // error, we'd do lookahead to try to do better recovery.
1134  if (isValidAfterIdentifierInDeclarator(NextToken())) {
1135    // If this token is valid for implicit int, e.g. "static x = 4", then
1136    // we just avoid eating the identifier, so it will be parsed as the
1137    // identifier in the declarator.
1138    return false;
1139  }
1140
1141  // Otherwise, if we don't consume this token, we are going to emit an
1142  // error anyway.  Try to recover from various common problems.  Check
1143  // to see if this was a reference to a tag name without a tag specified.
1144  // This is a common problem in C (saying 'foo' instead of 'struct foo').
1145  //
1146  // C++ doesn't need this, and isTagName doesn't take SS.
1147  if (SS == 0) {
1148    const char *TagName = 0, *FixitTagName = 0;
1149    tok::TokenKind TagKind = tok::unknown;
1150
1151    switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
1152      default: break;
1153      case DeclSpec::TST_enum:
1154        TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
1155      case DeclSpec::TST_union:
1156        TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
1157      case DeclSpec::TST_struct:
1158        TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
1159      case DeclSpec::TST_class:
1160        TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
1161    }
1162
1163    if (TagName) {
1164      Diag(Loc, diag::err_use_of_tag_name_without_tag)
1165        << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus
1166        << FixItHint::CreateInsertion(Tok.getLocation(),FixitTagName);
1167
1168      // Parse this as a tag as if the missing tag were present.
1169      if (TagKind == tok::kw_enum)
1170        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1171      else
1172        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
1173      return true;
1174    }
1175  }
1176
1177  // This is almost certainly an invalid type name. Let the action emit a
1178  // diagnostic and attempt to recover.
1179  ParsedType T;
1180  if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
1181                                      getCurScope(), SS, T)) {
1182    // The action emitted a diagnostic, so we don't have to.
1183    if (T) {
1184      // The action has suggested that the type T could be used. Set that as
1185      // the type in the declaration specifiers, consume the would-be type
1186      // name token, and we're done.
1187      const char *PrevSpec;
1188      unsigned DiagID;
1189      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
1190      DS.SetRangeEnd(Tok.getLocation());
1191      ConsumeToken();
1192
1193      // There may be other declaration specifiers after this.
1194      return true;
1195    }
1196
1197    // Fall through; the action had no suggestion for us.
1198  } else {
1199    // The action did not emit a diagnostic, so emit one now.
1200    SourceRange R;
1201    if (SS) R = SS->getRange();
1202    Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
1203  }
1204
1205  // Mark this as an error.
1206  const char *PrevSpec;
1207  unsigned DiagID;
1208  DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
1209  DS.SetRangeEnd(Tok.getLocation());
1210  ConsumeToken();
1211
1212  // TODO: Could inject an invalid typedef decl in an enclosing scope to
1213  // avoid rippling error messages on subsequent uses of the same type,
1214  // could be useful if #include was forgotten.
1215  return false;
1216}
1217
1218/// \brief Determine the declaration specifier context from the declarator
1219/// context.
1220///
1221/// \param Context the declarator context, which is one of the
1222/// Declarator::TheContext enumerator values.
1223Parser::DeclSpecContext
1224Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
1225  if (Context == Declarator::MemberContext)
1226    return DSC_class;
1227  if (Context == Declarator::FileContext)
1228    return DSC_top_level;
1229  return DSC_normal;
1230}
1231
1232/// ParseDeclarationSpecifiers
1233///       declaration-specifiers: [C99 6.7]
1234///         storage-class-specifier declaration-specifiers[opt]
1235///         type-specifier declaration-specifiers[opt]
1236/// [C99]   function-specifier declaration-specifiers[opt]
1237/// [GNU]   attributes declaration-specifiers[opt]
1238///
1239///       storage-class-specifier: [C99 6.7.1]
1240///         'typedef'
1241///         'extern'
1242///         'static'
1243///         'auto'
1244///         'register'
1245/// [C++]   'mutable'
1246/// [GNU]   '__thread'
1247///       function-specifier: [C99 6.7.4]
1248/// [C99]   'inline'
1249/// [C++]   'virtual'
1250/// [C++]   'explicit'
1251/// [OpenCL] '__kernel'
1252///       'friend': [C++ dcl.friend]
1253///       'constexpr': [C++0x dcl.constexpr]
1254
1255///
1256void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
1257                                        const ParsedTemplateInfo &TemplateInfo,
1258                                        AccessSpecifier AS,
1259                                        DeclSpecContext DSContext) {
1260  if (DS.getSourceRange().isInvalid()) {
1261    DS.SetRangeStart(Tok.getLocation());
1262    DS.SetRangeEnd(Tok.getLocation());
1263  }
1264
1265  while (1) {
1266    bool isInvalid = false;
1267    const char *PrevSpec = 0;
1268    unsigned DiagID = 0;
1269
1270    SourceLocation Loc = Tok.getLocation();
1271
1272    switch (Tok.getKind()) {
1273    default:
1274    DoneWithDeclSpec:
1275      // If this is not a declaration specifier token, we're done reading decl
1276      // specifiers.  First verify that DeclSpec's are consistent.
1277      DS.Finish(Diags, PP);
1278      return;
1279
1280    case tok::code_completion: {
1281      Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
1282      if (DS.hasTypeSpecifier()) {
1283        bool AllowNonIdentifiers
1284          = (getCurScope()->getFlags() & (Scope::ControlScope |
1285                                          Scope::BlockScope |
1286                                          Scope::TemplateParamScope |
1287                                          Scope::FunctionPrototypeScope |
1288                                          Scope::AtCatchScope)) == 0;
1289        bool AllowNestedNameSpecifiers
1290          = DSContext == DSC_top_level ||
1291            (DSContext == DSC_class && DS.isFriendSpecified());
1292
1293        Actions.CodeCompleteDeclSpec(getCurScope(), DS,
1294                                     AllowNonIdentifiers,
1295                                     AllowNestedNameSpecifiers);
1296        ConsumeCodeCompletionToken();
1297        return;
1298      }
1299
1300      if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
1301        CCC = Sema::PCC_LocalDeclarationSpecifiers;
1302      else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
1303        CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
1304                                    : Sema::PCC_Template;
1305      else if (DSContext == DSC_class)
1306        CCC = Sema::PCC_Class;
1307      else if (ObjCImpDecl)
1308        CCC = Sema::PCC_ObjCImplementation;
1309
1310      Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
1311      ConsumeCodeCompletionToken();
1312      return;
1313    }
1314
1315    case tok::coloncolon: // ::foo::bar
1316      // C++ scope specifier.  Annotate and loop, or bail out on error.
1317      if (TryAnnotateCXXScopeToken(true)) {
1318        if (!DS.hasTypeSpecifier())
1319          DS.SetTypeSpecError();
1320        goto DoneWithDeclSpec;
1321      }
1322      if (Tok.is(tok::coloncolon)) // ::new or ::delete
1323        goto DoneWithDeclSpec;
1324      continue;
1325
1326    case tok::annot_cxxscope: {
1327      if (DS.hasTypeSpecifier())
1328        goto DoneWithDeclSpec;
1329
1330      CXXScopeSpec SS;
1331      Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1332                                                   Tok.getAnnotationRange(),
1333                                                   SS);
1334
1335      // We are looking for a qualified typename.
1336      Token Next = NextToken();
1337      if (Next.is(tok::annot_template_id) &&
1338          static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
1339            ->Kind == TNK_Type_template) {
1340        // We have a qualified template-id, e.g., N::A<int>
1341
1342        // C++ [class.qual]p2:
1343        //   In a lookup in which the constructor is an acceptable lookup
1344        //   result and the nested-name-specifier nominates a class C:
1345        //
1346        //     - if the name specified after the
1347        //       nested-name-specifier, when looked up in C, is the
1348        //       injected-class-name of C (Clause 9), or
1349        //
1350        //     - if the name specified after the nested-name-specifier
1351        //       is the same as the identifier or the
1352        //       simple-template-id's template-name in the last
1353        //       component of the nested-name-specifier,
1354        //
1355        //   the name is instead considered to name the constructor of
1356        //   class C.
1357        //
1358        // Thus, if the template-name is actually the constructor
1359        // name, then the code is ill-formed; this interpretation is
1360        // reinforced by the NAD status of core issue 635.
1361        TemplateIdAnnotation *TemplateId
1362          = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue());
1363        if ((DSContext == DSC_top_level ||
1364             (DSContext == DSC_class && DS.isFriendSpecified())) &&
1365            TemplateId->Name &&
1366            Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
1367          if (isConstructorDeclarator()) {
1368            // The user meant this to be an out-of-line constructor
1369            // definition, but template arguments are not allowed
1370            // there.  Just allow this as a constructor; we'll
1371            // complain about it later.
1372            goto DoneWithDeclSpec;
1373          }
1374
1375          // The user meant this to name a type, but it actually names
1376          // a constructor with some extraneous template
1377          // arguments. Complain, then parse it as a type as the user
1378          // intended.
1379          Diag(TemplateId->TemplateNameLoc,
1380               diag::err_out_of_line_template_id_names_constructor)
1381            << TemplateId->Name;
1382        }
1383
1384        DS.getTypeSpecScope() = SS;
1385        ConsumeToken(); // The C++ scope.
1386        assert(Tok.is(tok::annot_template_id) &&
1387               "ParseOptionalCXXScopeSpecifier not working");
1388        AnnotateTemplateIdTokenAsType();
1389        continue;
1390      }
1391
1392      if (Next.is(tok::annot_typename)) {
1393        DS.getTypeSpecScope() = SS;
1394        ConsumeToken(); // The C++ scope.
1395        if (Tok.getAnnotationValue()) {
1396          ParsedType T = getTypeAnnotation(Tok);
1397          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1398                                         Tok.getAnnotationEndLoc(),
1399                                         PrevSpec, DiagID, T);
1400        }
1401        else
1402          DS.SetTypeSpecError();
1403        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1404        ConsumeToken(); // The typename
1405      }
1406
1407      if (Next.isNot(tok::identifier))
1408        goto DoneWithDeclSpec;
1409
1410      // If we're in a context where the identifier could be a class name,
1411      // check whether this is a constructor declaration.
1412      if ((DSContext == DSC_top_level ||
1413           (DSContext == DSC_class && DS.isFriendSpecified())) &&
1414          Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
1415                                     &SS)) {
1416        if (isConstructorDeclarator())
1417          goto DoneWithDeclSpec;
1418
1419        // As noted in C++ [class.qual]p2 (cited above), when the name
1420        // of the class is qualified in a context where it could name
1421        // a constructor, its a constructor name. However, we've
1422        // looked at the declarator, and the user probably meant this
1423        // to be a type. Complain that it isn't supposed to be treated
1424        // as a type, then proceed to parse it as a type.
1425        Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
1426          << Next.getIdentifierInfo();
1427      }
1428
1429      ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
1430                                               Next.getLocation(),
1431                                               getCurScope(), &SS,
1432                                               false, false, ParsedType(),
1433                                               /*NonTrivialSourceInfo=*/true);
1434
1435      // If the referenced identifier is not a type, then this declspec is
1436      // erroneous: We already checked about that it has no type specifier, and
1437      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
1438      // typename.
1439      if (TypeRep == 0) {
1440        ConsumeToken();   // Eat the scope spec so the identifier is current.
1441        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
1442        goto DoneWithDeclSpec;
1443      }
1444
1445      DS.getTypeSpecScope() = SS;
1446      ConsumeToken(); // The C++ scope.
1447
1448      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1449                                     DiagID, TypeRep);
1450      if (isInvalid)
1451        break;
1452
1453      DS.SetRangeEnd(Tok.getLocation());
1454      ConsumeToken(); // The typename.
1455
1456      continue;
1457    }
1458
1459    case tok::annot_typename: {
1460      if (Tok.getAnnotationValue()) {
1461        ParsedType T = getTypeAnnotation(Tok);
1462        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1463                                       DiagID, T);
1464      } else
1465        DS.SetTypeSpecError();
1466
1467      if (isInvalid)
1468        break;
1469
1470      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1471      ConsumeToken(); // The typename
1472
1473      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1474      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1475      // Objective-C interface.
1476      if (Tok.is(tok::less) && getLang().ObjC1)
1477        ParseObjCProtocolQualifiers(DS);
1478
1479      continue;
1480    }
1481
1482    case tok::kw___is_signed:
1483      // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
1484      // typically treats it as a trait. If we see __is_signed as it appears
1485      // in libstdc++, e.g.,
1486      //
1487      //   static const bool __is_signed;
1488      //
1489      // then treat __is_signed as an identifier rather than as a keyword.
1490      if (DS.getTypeSpecType() == TST_bool &&
1491          DS.getTypeQualifiers() == DeclSpec::TQ_const &&
1492          DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1493        Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
1494        Tok.setKind(tok::identifier);
1495      }
1496
1497      // We're done with the declaration-specifiers.
1498      goto DoneWithDeclSpec;
1499
1500      // typedef-name
1501    case tok::identifier: {
1502      // In C++, check to see if this is a scope specifier like foo::bar::, if
1503      // so handle it as such.  This is important for ctor parsing.
1504      if (getLang().CPlusPlus) {
1505        if (TryAnnotateCXXScopeToken(true)) {
1506          if (!DS.hasTypeSpecifier())
1507            DS.SetTypeSpecError();
1508          goto DoneWithDeclSpec;
1509        }
1510        if (!Tok.is(tok::identifier))
1511          continue;
1512      }
1513
1514      // This identifier can only be a typedef name if we haven't already seen
1515      // a type-specifier.  Without this check we misparse:
1516      //  typedef int X; struct Y { short X; };  as 'short int'.
1517      if (DS.hasTypeSpecifier())
1518        goto DoneWithDeclSpec;
1519
1520      // Check for need to substitute AltiVec keyword tokens.
1521      if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1522        break;
1523
1524      // It has to be available as a typedef too!
1525      ParsedType TypeRep =
1526        Actions.getTypeName(*Tok.getIdentifierInfo(),
1527                            Tok.getLocation(), getCurScope());
1528
1529      // If this is not a typedef name, don't parse it as part of the declspec,
1530      // it must be an implicit int or an error.
1531      if (!TypeRep) {
1532        if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
1533        goto DoneWithDeclSpec;
1534      }
1535
1536      // If we're in a context where the identifier could be a class name,
1537      // check whether this is a constructor declaration.
1538      if (getLang().CPlusPlus && DSContext == DSC_class &&
1539          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
1540          isConstructorDeclarator())
1541        goto DoneWithDeclSpec;
1542
1543      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1544                                     DiagID, TypeRep);
1545      if (isInvalid)
1546        break;
1547
1548      DS.SetRangeEnd(Tok.getLocation());
1549      ConsumeToken(); // The identifier
1550
1551      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1552      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1553      // Objective-C interface.
1554      if (Tok.is(tok::less) && getLang().ObjC1)
1555        ParseObjCProtocolQualifiers(DS);
1556
1557      // Need to support trailing type qualifiers (e.g. "id<p> const").
1558      // If a type specifier follows, it will be diagnosed elsewhere.
1559      continue;
1560    }
1561
1562      // type-name
1563    case tok::annot_template_id: {
1564      TemplateIdAnnotation *TemplateId
1565        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1566      if (TemplateId->Kind != TNK_Type_template) {
1567        // This template-id does not refer to a type name, so we're
1568        // done with the type-specifiers.
1569        goto DoneWithDeclSpec;
1570      }
1571
1572      // If we're in a context where the template-id could be a
1573      // constructor name or specialization, check whether this is a
1574      // constructor declaration.
1575      if (getLang().CPlusPlus && DSContext == DSC_class &&
1576          Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
1577          isConstructorDeclarator())
1578        goto DoneWithDeclSpec;
1579
1580      // Turn the template-id annotation token into a type annotation
1581      // token, then try again to parse it as a type-specifier.
1582      AnnotateTemplateIdTokenAsType();
1583      continue;
1584    }
1585
1586    // GNU attributes support.
1587    case tok::kw___attribute:
1588      ParseGNUAttributes(DS.getAttributes());
1589      continue;
1590
1591    // Microsoft declspec support.
1592    case tok::kw___declspec:
1593      ParseMicrosoftDeclSpec(DS.getAttributes());
1594      continue;
1595
1596    // Microsoft single token adornments.
1597    case tok::kw___forceinline:
1598      // FIXME: Add handling here!
1599      break;
1600
1601    case tok::kw___ptr64:
1602    case tok::kw___w64:
1603    case tok::kw___cdecl:
1604    case tok::kw___stdcall:
1605    case tok::kw___fastcall:
1606    case tok::kw___thiscall:
1607      ParseMicrosoftTypeAttributes(DS.getAttributes());
1608      continue;
1609
1610    // Borland single token adornments.
1611    case tok::kw___pascal:
1612      ParseBorlandTypeAttributes(DS.getAttributes());
1613      continue;
1614
1615    // OpenCL single token adornments.
1616    case tok::kw___kernel:
1617      ParseOpenCLAttributes(DS.getAttributes());
1618      continue;
1619
1620    // storage-class-specifier
1621    case tok::kw_typedef:
1622      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
1623                                         DiagID, getLang());
1624      break;
1625    case tok::kw_extern:
1626      if (DS.isThreadSpecified())
1627        Diag(Tok, diag::ext_thread_before) << "extern";
1628      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1629                                         DiagID, getLang());
1630      break;
1631    case tok::kw___private_extern__:
1632      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1633                                         PrevSpec, DiagID, getLang());
1634      break;
1635    case tok::kw_static:
1636      if (DS.isThreadSpecified())
1637        Diag(Tok, diag::ext_thread_before) << "static";
1638      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1639                                         DiagID, getLang());
1640      break;
1641    case tok::kw_auto:
1642      if (getLang().CPlusPlus0x) {
1643        if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
1644          isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1645                                           DiagID, getLang());
1646          if (!isInvalid)
1647            Diag(Tok, diag::auto_storage_class)
1648              << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
1649        }
1650        else
1651          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1652                                         DiagID);
1653      }
1654      else
1655        isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1656                                           DiagID, getLang());
1657      break;
1658    case tok::kw_register:
1659      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1660                                         DiagID, getLang());
1661      break;
1662    case tok::kw_mutable:
1663      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1664                                         DiagID, getLang());
1665      break;
1666    case tok::kw___thread:
1667      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1668      break;
1669
1670    // function-specifier
1671    case tok::kw_inline:
1672      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1673      break;
1674    case tok::kw_virtual:
1675      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1676      break;
1677    case tok::kw_explicit:
1678      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1679      break;
1680
1681    // friend
1682    case tok::kw_friend:
1683      if (DSContext == DSC_class)
1684        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1685      else {
1686        PrevSpec = ""; // not actually used by the diagnostic
1687        DiagID = diag::err_friend_invalid_in_context;
1688        isInvalid = true;
1689      }
1690      break;
1691
1692    // constexpr
1693    case tok::kw_constexpr:
1694      isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
1695      break;
1696
1697    // type-specifier
1698    case tok::kw_short:
1699      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1700                                      DiagID);
1701      break;
1702    case tok::kw_long:
1703      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1704        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1705                                        DiagID);
1706      else
1707        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1708                                        DiagID);
1709      break;
1710    case tok::kw___int64:
1711        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1712                                        DiagID);
1713      break;
1714    case tok::kw_signed:
1715      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1716                                     DiagID);
1717      break;
1718    case tok::kw_unsigned:
1719      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1720                                     DiagID);
1721      break;
1722    case tok::kw__Complex:
1723      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1724                                        DiagID);
1725      break;
1726    case tok::kw__Imaginary:
1727      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1728                                        DiagID);
1729      break;
1730    case tok::kw_void:
1731      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1732                                     DiagID);
1733      break;
1734    case tok::kw_char:
1735      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1736                                     DiagID);
1737      break;
1738    case tok::kw_int:
1739      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1740                                     DiagID);
1741      break;
1742    case tok::kw_float:
1743      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1744                                     DiagID);
1745      break;
1746    case tok::kw_double:
1747      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1748                                     DiagID);
1749      break;
1750    case tok::kw_wchar_t:
1751      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1752                                     DiagID);
1753      break;
1754    case tok::kw_char16_t:
1755      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1756                                     DiagID);
1757      break;
1758    case tok::kw_char32_t:
1759      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1760                                     DiagID);
1761      break;
1762    case tok::kw_bool:
1763    case tok::kw__Bool:
1764      if (Tok.is(tok::kw_bool) &&
1765          DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
1766          DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1767        PrevSpec = ""; // Not used by the diagnostic.
1768        DiagID = diag::err_bool_redeclaration;
1769        // For better error recovery.
1770        Tok.setKind(tok::identifier);
1771        isInvalid = true;
1772      } else {
1773        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1774                                       DiagID);
1775      }
1776      break;
1777    case tok::kw__Decimal32:
1778      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1779                                     DiagID);
1780      break;
1781    case tok::kw__Decimal64:
1782      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1783                                     DiagID);
1784      break;
1785    case tok::kw__Decimal128:
1786      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1787                                     DiagID);
1788      break;
1789    case tok::kw___vector:
1790      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1791      break;
1792    case tok::kw___pixel:
1793      isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1794      break;
1795    case tok::kw___unknown_anytype:
1796      isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
1797                                     PrevSpec, DiagID);
1798      break;
1799
1800    // class-specifier:
1801    case tok::kw_class:
1802    case tok::kw_struct:
1803    case tok::kw_union: {
1804      tok::TokenKind Kind = Tok.getKind();
1805      ConsumeToken();
1806      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1807      continue;
1808    }
1809
1810    // enum-specifier:
1811    case tok::kw_enum:
1812      ConsumeToken();
1813      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1814      continue;
1815
1816    // cv-qualifier:
1817    case tok::kw_const:
1818      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1819                                 getLang());
1820      break;
1821    case tok::kw_volatile:
1822      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1823                                 getLang());
1824      break;
1825    case tok::kw_restrict:
1826      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1827                                 getLang());
1828      break;
1829
1830    // C++ typename-specifier:
1831    case tok::kw_typename:
1832      if (TryAnnotateTypeOrScopeToken()) {
1833        DS.SetTypeSpecError();
1834        goto DoneWithDeclSpec;
1835      }
1836      if (!Tok.is(tok::kw_typename))
1837        continue;
1838      break;
1839
1840    // GNU typeof support.
1841    case tok::kw_typeof:
1842      ParseTypeofSpecifier(DS);
1843      continue;
1844
1845    case tok::kw_decltype:
1846      ParseDecltypeSpecifier(DS);
1847      continue;
1848
1849    // OpenCL qualifiers:
1850    case tok::kw_private:
1851      if (!getLang().OpenCL)
1852        goto DoneWithDeclSpec;
1853    case tok::kw___private:
1854    case tok::kw___global:
1855    case tok::kw___local:
1856    case tok::kw___constant:
1857    case tok::kw___read_only:
1858    case tok::kw___write_only:
1859    case tok::kw___read_write:
1860      ParseOpenCLQualifiers(DS);
1861      break;
1862
1863    case tok::less:
1864      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1865      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
1866      // but we support it.
1867      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1868        goto DoneWithDeclSpec;
1869
1870      if (!ParseObjCProtocolQualifiers(DS))
1871        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1872          << FixItHint::CreateInsertion(Loc, "id")
1873          << SourceRange(Loc, DS.getSourceRange().getEnd());
1874
1875      // Need to support trailing type qualifiers (e.g. "id<p> const").
1876      // If a type specifier follows, it will be diagnosed elsewhere.
1877      continue;
1878    }
1879    // If the specifier wasn't legal, issue a diagnostic.
1880    if (isInvalid) {
1881      assert(PrevSpec && "Method did not return previous specifier!");
1882      assert(DiagID);
1883
1884      if (DiagID == diag::ext_duplicate_declspec)
1885        Diag(Tok, DiagID)
1886          << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
1887      else
1888        Diag(Tok, DiagID) << PrevSpec;
1889    }
1890
1891    DS.SetRangeEnd(Tok.getLocation());
1892    if (DiagID != diag::err_bool_redeclaration)
1893      ConsumeToken();
1894  }
1895}
1896
1897/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1898/// primarily follow the C++ grammar with additions for C99 and GNU,
1899/// which together subsume the C grammar. Note that the C++
1900/// type-specifier also includes the C type-qualifier (for const,
1901/// volatile, and C99 restrict). Returns true if a type-specifier was
1902/// found (and parsed), false otherwise.
1903///
1904///       type-specifier: [C++ 7.1.5]
1905///         simple-type-specifier
1906///         class-specifier
1907///         enum-specifier
1908///         elaborated-type-specifier  [TODO]
1909///         cv-qualifier
1910///
1911///       cv-qualifier: [C++ 7.1.5.1]
1912///         'const'
1913///         'volatile'
1914/// [C99]   'restrict'
1915///
1916///       simple-type-specifier: [ C++ 7.1.5.2]
1917///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
1918///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
1919///         'char'
1920///         'wchar_t'
1921///         'bool'
1922///         'short'
1923///         'int'
1924///         'long'
1925///         'signed'
1926///         'unsigned'
1927///         'float'
1928///         'double'
1929///         'void'
1930/// [C99]   '_Bool'
1931/// [C99]   '_Complex'
1932/// [C99]   '_Imaginary'  // Removed in TC2?
1933/// [GNU]   '_Decimal32'
1934/// [GNU]   '_Decimal64'
1935/// [GNU]   '_Decimal128'
1936/// [GNU]   typeof-specifier
1937/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
1938/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
1939/// [C++0x] 'decltype' ( expression )
1940/// [AltiVec] '__vector'
1941bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1942                                        const char *&PrevSpec,
1943                                        unsigned &DiagID,
1944                                        const ParsedTemplateInfo &TemplateInfo,
1945                                        bool SuppressDeclarations) {
1946  SourceLocation Loc = Tok.getLocation();
1947
1948  switch (Tok.getKind()) {
1949  case tok::identifier:   // foo::bar
1950    // If we already have a type specifier, this identifier is not a type.
1951    if (DS.getTypeSpecType() != DeclSpec::TST_unspecified ||
1952        DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
1953        DS.getTypeSpecSign() != DeclSpec::TSS_unspecified)
1954      return false;
1955    // Check for need to substitute AltiVec keyword tokens.
1956    if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1957      break;
1958    // Fall through.
1959  case tok::kw_typename:  // typename foo::bar
1960    // Annotate typenames and C++ scope specifiers.  If we get one, just
1961    // recurse to handle whatever we get.
1962    if (TryAnnotateTypeOrScopeToken())
1963      return true;
1964    if (Tok.is(tok::identifier))
1965      return false;
1966    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1967                                      TemplateInfo, SuppressDeclarations);
1968  case tok::coloncolon:   // ::foo::bar
1969    if (NextToken().is(tok::kw_new) ||    // ::new
1970        NextToken().is(tok::kw_delete))   // ::delete
1971      return false;
1972
1973    // Annotate typenames and C++ scope specifiers.  If we get one, just
1974    // recurse to handle whatever we get.
1975    if (TryAnnotateTypeOrScopeToken())
1976      return true;
1977    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1978                                      TemplateInfo, SuppressDeclarations);
1979
1980  // simple-type-specifier:
1981  case tok::annot_typename: {
1982    if (ParsedType T = getTypeAnnotation(Tok)) {
1983      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1984                                     Tok.getAnnotationEndLoc(), PrevSpec,
1985                                     DiagID, T);
1986    } else
1987      DS.SetTypeSpecError();
1988    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1989    ConsumeToken(); // The typename
1990
1991    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1992    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1993    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1994    // just a normal reference to a typedef name.
1995    if (Tok.is(tok::less) && getLang().ObjC1)
1996      ParseObjCProtocolQualifiers(DS);
1997
1998    return true;
1999  }
2000
2001  case tok::kw_short:
2002    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
2003    break;
2004  case tok::kw_long:
2005    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
2006      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
2007                                      DiagID);
2008    else
2009      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2010                                      DiagID);
2011    break;
2012  case tok::kw___int64:
2013      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
2014                                      DiagID);
2015    break;
2016  case tok::kw_signed:
2017    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
2018    break;
2019  case tok::kw_unsigned:
2020    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
2021                                   DiagID);
2022    break;
2023  case tok::kw__Complex:
2024    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
2025                                      DiagID);
2026    break;
2027  case tok::kw__Imaginary:
2028    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
2029                                      DiagID);
2030    break;
2031  case tok::kw_void:
2032    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
2033    break;
2034  case tok::kw_char:
2035    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
2036    break;
2037  case tok::kw_int:
2038    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
2039    break;
2040  case tok::kw_float:
2041    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
2042    break;
2043  case tok::kw_double:
2044    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
2045    break;
2046  case tok::kw_wchar_t:
2047    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
2048    break;
2049  case tok::kw_char16_t:
2050    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
2051    break;
2052  case tok::kw_char32_t:
2053    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
2054    break;
2055  case tok::kw_bool:
2056  case tok::kw__Bool:
2057    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
2058    break;
2059  case tok::kw__Decimal32:
2060    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
2061                                   DiagID);
2062    break;
2063  case tok::kw__Decimal64:
2064    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
2065                                   DiagID);
2066    break;
2067  case tok::kw__Decimal128:
2068    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
2069                                   DiagID);
2070    break;
2071  case tok::kw___vector:
2072    isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
2073    break;
2074  case tok::kw___pixel:
2075    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
2076    break;
2077
2078  // class-specifier:
2079  case tok::kw_class:
2080  case tok::kw_struct:
2081  case tok::kw_union: {
2082    tok::TokenKind Kind = Tok.getKind();
2083    ConsumeToken();
2084    ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none,
2085                        SuppressDeclarations);
2086    return true;
2087  }
2088
2089  // enum-specifier:
2090  case tok::kw_enum:
2091    ConsumeToken();
2092    ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none);
2093    return true;
2094
2095  // cv-qualifier:
2096  case tok::kw_const:
2097    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
2098                               DiagID, getLang());
2099    break;
2100  case tok::kw_volatile:
2101    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
2102                               DiagID, getLang());
2103    break;
2104  case tok::kw_restrict:
2105    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
2106                               DiagID, getLang());
2107    break;
2108
2109  // GNU typeof support.
2110  case tok::kw_typeof:
2111    ParseTypeofSpecifier(DS);
2112    return true;
2113
2114  // C++0x decltype support.
2115  case tok::kw_decltype:
2116    ParseDecltypeSpecifier(DS);
2117    return true;
2118
2119  // OpenCL qualifiers:
2120  case tok::kw_private:
2121    if (!getLang().OpenCL)
2122      return false;
2123  case tok::kw___private:
2124  case tok::kw___global:
2125  case tok::kw___local:
2126  case tok::kw___constant:
2127  case tok::kw___read_only:
2128  case tok::kw___write_only:
2129  case tok::kw___read_write:
2130    ParseOpenCLQualifiers(DS);
2131    break;
2132
2133  // C++0x auto support.
2134  case tok::kw_auto:
2135    if (!getLang().CPlusPlus0x)
2136      return false;
2137
2138    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
2139    break;
2140
2141  case tok::kw___ptr64:
2142  case tok::kw___w64:
2143  case tok::kw___cdecl:
2144  case tok::kw___stdcall:
2145  case tok::kw___fastcall:
2146  case tok::kw___thiscall:
2147    ParseMicrosoftTypeAttributes(DS.getAttributes());
2148    return true;
2149
2150  case tok::kw___pascal:
2151    ParseBorlandTypeAttributes(DS.getAttributes());
2152    return true;
2153
2154  default:
2155    // Not a type-specifier; do nothing.
2156    return false;
2157  }
2158
2159  // If the specifier combination wasn't legal, issue a diagnostic.
2160  if (isInvalid) {
2161    assert(PrevSpec && "Method did not return previous specifier!");
2162    // Pick between error or extwarn.
2163    Diag(Tok, DiagID) << PrevSpec;
2164  }
2165  DS.SetRangeEnd(Tok.getLocation());
2166  ConsumeToken(); // whatever we parsed above.
2167  return true;
2168}
2169
2170/// ParseStructDeclaration - Parse a struct declaration without the terminating
2171/// semicolon.
2172///
2173///       struct-declaration:
2174///         specifier-qualifier-list struct-declarator-list
2175/// [GNU]   __extension__ struct-declaration
2176/// [GNU]   specifier-qualifier-list
2177///       struct-declarator-list:
2178///         struct-declarator
2179///         struct-declarator-list ',' struct-declarator
2180/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
2181///       struct-declarator:
2182///         declarator
2183/// [GNU]   declarator attributes[opt]
2184///         declarator[opt] ':' constant-expression
2185/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
2186///
2187void Parser::
2188ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
2189  if (Tok.is(tok::kw___extension__)) {
2190    // __extension__ silences extension warnings in the subexpression.
2191    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
2192    ConsumeToken();
2193    return ParseStructDeclaration(DS, Fields);
2194  }
2195
2196  // Parse the common specifier-qualifiers-list piece.
2197  ParseSpecifierQualifierList(DS);
2198
2199  // If there are no declarators, this is a free-standing declaration
2200  // specifier. Let the actions module cope with it.
2201  if (Tok.is(tok::semi)) {
2202    Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS);
2203    return;
2204  }
2205
2206  // Read struct-declarators until we find the semicolon.
2207  bool FirstDeclarator = true;
2208  while (1) {
2209    ParsingDeclRAIIObject PD(*this);
2210    FieldDeclarator DeclaratorInfo(DS);
2211
2212    // Attributes are only allowed here on successive declarators.
2213    if (!FirstDeclarator)
2214      MaybeParseGNUAttributes(DeclaratorInfo.D);
2215
2216    /// struct-declarator: declarator
2217    /// struct-declarator: declarator[opt] ':' constant-expression
2218    if (Tok.isNot(tok::colon)) {
2219      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2220      ColonProtectionRAIIObject X(*this);
2221      ParseDeclarator(DeclaratorInfo.D);
2222    }
2223
2224    if (Tok.is(tok::colon)) {
2225      ConsumeToken();
2226      ExprResult Res(ParseConstantExpression());
2227      if (Res.isInvalid())
2228        SkipUntil(tok::semi, true, true);
2229      else
2230        DeclaratorInfo.BitfieldSize = Res.release();
2231    }
2232
2233    // If attributes exist after the declarator, parse them.
2234    MaybeParseGNUAttributes(DeclaratorInfo.D);
2235
2236    // We're done with this declarator;  invoke the callback.
2237    Decl *D = Fields.invoke(DeclaratorInfo);
2238    PD.complete(D);
2239
2240    // If we don't have a comma, it is either the end of the list (a ';')
2241    // or an error, bail out.
2242    if (Tok.isNot(tok::comma))
2243      return;
2244
2245    // Consume the comma.
2246    ConsumeToken();
2247
2248    FirstDeclarator = false;
2249  }
2250}
2251
2252/// ParseStructUnionBody
2253///       struct-contents:
2254///         struct-declaration-list
2255/// [EXT]   empty
2256/// [GNU]   "struct-declaration-list" without terminatoring ';'
2257///       struct-declaration-list:
2258///         struct-declaration
2259///         struct-declaration-list struct-declaration
2260/// [OBC]   '@' 'defs' '(' class-name ')'
2261///
2262void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
2263                                  unsigned TagType, Decl *TagDecl) {
2264  PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2265                                      "parsing struct/union body");
2266
2267  SourceLocation LBraceLoc = ConsumeBrace();
2268
2269  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
2270  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2271
2272  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
2273  // C++.
2274  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
2275    Diag(Tok, diag::ext_empty_struct_union)
2276      << (TagType == TST_union);
2277
2278  llvm::SmallVector<Decl *, 32> FieldDecls;
2279
2280  // While we still have something to read, read the declarations in the struct.
2281  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2282    // Each iteration of this loop reads one struct-declaration.
2283
2284    // Check for extraneous top-level semicolon.
2285    if (Tok.is(tok::semi)) {
2286      Diag(Tok, diag::ext_extra_struct_semi)
2287        << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
2288        << FixItHint::CreateRemoval(Tok.getLocation());
2289      ConsumeToken();
2290      continue;
2291    }
2292
2293    // Parse all the comma separated declarators.
2294    DeclSpec DS(AttrFactory);
2295
2296    if (!Tok.is(tok::at)) {
2297      struct CFieldCallback : FieldCallback {
2298        Parser &P;
2299        Decl *TagDecl;
2300        llvm::SmallVectorImpl<Decl *> &FieldDecls;
2301
2302        CFieldCallback(Parser &P, Decl *TagDecl,
2303                       llvm::SmallVectorImpl<Decl *> &FieldDecls) :
2304          P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
2305
2306        virtual Decl *invoke(FieldDeclarator &FD) {
2307          // Install the declarator into the current TagDecl.
2308          Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
2309                              FD.D.getDeclSpec().getSourceRange().getBegin(),
2310                                                 FD.D, FD.BitfieldSize);
2311          FieldDecls.push_back(Field);
2312          return Field;
2313        }
2314      } Callback(*this, TagDecl, FieldDecls);
2315
2316      ParseStructDeclaration(DS, Callback);
2317    } else { // Handle @defs
2318      ConsumeToken();
2319      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
2320        Diag(Tok, diag::err_unexpected_at);
2321        SkipUntil(tok::semi, true);
2322        continue;
2323      }
2324      ConsumeToken();
2325      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
2326      if (!Tok.is(tok::identifier)) {
2327        Diag(Tok, diag::err_expected_ident);
2328        SkipUntil(tok::semi, true);
2329        continue;
2330      }
2331      llvm::SmallVector<Decl *, 16> Fields;
2332      Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
2333                        Tok.getIdentifierInfo(), Fields);
2334      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
2335      ConsumeToken();
2336      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
2337    }
2338
2339    if (Tok.is(tok::semi)) {
2340      ConsumeToken();
2341    } else if (Tok.is(tok::r_brace)) {
2342      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
2343      break;
2344    } else {
2345      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
2346      // Skip to end of block or statement to avoid ext-warning on extra ';'.
2347      SkipUntil(tok::r_brace, true, true);
2348      // If we stopped at a ';', eat it.
2349      if (Tok.is(tok::semi)) ConsumeToken();
2350    }
2351  }
2352
2353  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2354
2355  ParsedAttributes attrs(AttrFactory);
2356  // If attributes exist after struct contents, parse them.
2357  MaybeParseGNUAttributes(attrs);
2358
2359  Actions.ActOnFields(getCurScope(),
2360                      RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
2361                      LBraceLoc, RBraceLoc,
2362                      attrs.getList());
2363  StructScope.Exit();
2364  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc);
2365}
2366
2367/// ParseEnumSpecifier
2368///       enum-specifier: [C99 6.7.2.2]
2369///         'enum' identifier[opt] '{' enumerator-list '}'
2370///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
2371/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
2372///                                                 '}' attributes[opt]
2373///         'enum' identifier
2374/// [GNU]   'enum' attributes[opt] identifier
2375///
2376/// [C++0x] enum-head '{' enumerator-list[opt] '}'
2377/// [C++0x] enum-head '{' enumerator-list ','  '}'
2378///
2379///       enum-head: [C++0x]
2380///         enum-key attributes[opt] identifier[opt] enum-base[opt]
2381///         enum-key attributes[opt] nested-name-specifier identifier enum-base[opt]
2382///
2383///       enum-key: [C++0x]
2384///         'enum'
2385///         'enum' 'class'
2386///         'enum' 'struct'
2387///
2388///       enum-base: [C++0x]
2389///         ':' type-specifier-seq
2390///
2391/// [C++] elaborated-type-specifier:
2392/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
2393///
2394void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
2395                                const ParsedTemplateInfo &TemplateInfo,
2396                                AccessSpecifier AS) {
2397  // Parse the tag portion of this.
2398  if (Tok.is(tok::code_completion)) {
2399    // Code completion for an enum name.
2400    Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
2401    ConsumeCodeCompletionToken();
2402  }
2403
2404  // If attributes exist after tag, parse them.
2405  ParsedAttributes attrs(AttrFactory);
2406  MaybeParseGNUAttributes(attrs);
2407
2408  CXXScopeSpec &SS = DS.getTypeSpecScope();
2409  if (getLang().CPlusPlus) {
2410    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false))
2411      return;
2412
2413    if (SS.isSet() && Tok.isNot(tok::identifier)) {
2414      Diag(Tok, diag::err_expected_ident);
2415      if (Tok.isNot(tok::l_brace)) {
2416        // Has no name and is not a definition.
2417        // Skip the rest of this declarator, up until the comma or semicolon.
2418        SkipUntil(tok::comma, true);
2419        return;
2420      }
2421    }
2422  }
2423
2424  bool AllowFixedUnderlyingType = getLang().CPlusPlus0x || getLang().Microsoft;
2425  bool IsScopedEnum = false;
2426  bool IsScopedUsingClassTag = false;
2427
2428  if (getLang().CPlusPlus0x &&
2429      (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
2430    IsScopedEnum = true;
2431    IsScopedUsingClassTag = Tok.is(tok::kw_class);
2432    ConsumeToken();
2433  }
2434
2435  // Must have either 'enum name' or 'enum {...}'.
2436  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
2437      (AllowFixedUnderlyingType && Tok.isNot(tok::colon))) {
2438    Diag(Tok, diag::err_expected_ident_lbrace);
2439
2440    // Skip the rest of this declarator, up until the comma or semicolon.
2441    SkipUntil(tok::comma, true);
2442    return;
2443  }
2444
2445  // If an identifier is present, consume and remember it.
2446  IdentifierInfo *Name = 0;
2447  SourceLocation NameLoc;
2448  if (Tok.is(tok::identifier)) {
2449    Name = Tok.getIdentifierInfo();
2450    NameLoc = ConsumeToken();
2451  }
2452
2453  if (!Name && IsScopedEnum) {
2454    // C++0x 7.2p2: The optional identifier shall not be omitted in the
2455    // declaration of a scoped enumeration.
2456    Diag(Tok, diag::err_scoped_enum_missing_identifier);
2457    IsScopedEnum = false;
2458    IsScopedUsingClassTag = false;
2459  }
2460
2461  TypeResult BaseType;
2462
2463  // Parse the fixed underlying type.
2464  if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
2465    bool PossibleBitfield = false;
2466    if (getCurScope()->getFlags() & Scope::ClassScope) {
2467      // If we're in class scope, this can either be an enum declaration with
2468      // an underlying type, or a declaration of a bitfield member. We try to
2469      // use a simple disambiguation scheme first to catch the common cases
2470      // (integer literal, sizeof); if it's still ambiguous, we then consider
2471      // anything that's a simple-type-specifier followed by '(' as an
2472      // expression. This suffices because function types are not valid
2473      // underlying types anyway.
2474      TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
2475      // If the next token starts an expression, we know we're parsing a
2476      // bit-field. This is the common case.
2477      if (TPR == TPResult::True())
2478        PossibleBitfield = true;
2479      // If the next token starts a type-specifier-seq, it may be either a
2480      // a fixed underlying type or the start of a function-style cast in C++;
2481      // lookahead one more token to see if it's obvious that we have a
2482      // fixed underlying type.
2483      else if (TPR == TPResult::False() &&
2484               GetLookAheadToken(2).getKind() == tok::semi) {
2485        // Consume the ':'.
2486        ConsumeToken();
2487      } else {
2488        // We have the start of a type-specifier-seq, so we have to perform
2489        // tentative parsing to determine whether we have an expression or a
2490        // type.
2491        TentativeParsingAction TPA(*this);
2492
2493        // Consume the ':'.
2494        ConsumeToken();
2495
2496        if ((getLang().CPlusPlus &&
2497             isCXXDeclarationSpecifier() != TPResult::True()) ||
2498            (!getLang().CPlusPlus && !isDeclarationSpecifier(true))) {
2499          // We'll parse this as a bitfield later.
2500          PossibleBitfield = true;
2501          TPA.Revert();
2502        } else {
2503          // We have a type-specifier-seq.
2504          TPA.Commit();
2505        }
2506      }
2507    } else {
2508      // Consume the ':'.
2509      ConsumeToken();
2510    }
2511
2512    if (!PossibleBitfield) {
2513      SourceRange Range;
2514      BaseType = ParseTypeName(&Range);
2515
2516      if (!getLang().CPlusPlus0x)
2517        Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type)
2518          << Range;
2519    }
2520  }
2521
2522  // There are three options here.  If we have 'enum foo;', then this is a
2523  // forward declaration.  If we have 'enum foo {...' then this is a
2524  // definition. Otherwise we have something like 'enum foo xyz', a reference.
2525  //
2526  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
2527  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
2528  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
2529  //
2530  Sema::TagUseKind TUK;
2531  if (Tok.is(tok::l_brace))
2532    TUK = Sema::TUK_Definition;
2533  else if (Tok.is(tok::semi))
2534    TUK = Sema::TUK_Declaration;
2535  else
2536    TUK = Sema::TUK_Reference;
2537
2538  // enums cannot be templates, although they can be referenced from a
2539  // template.
2540  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
2541      TUK != Sema::TUK_Reference) {
2542    Diag(Tok, diag::err_enum_template);
2543
2544    // Skip the rest of this declarator, up until the comma or semicolon.
2545    SkipUntil(tok::comma, true);
2546    return;
2547  }
2548
2549  if (!Name && TUK != Sema::TUK_Definition) {
2550    Diag(Tok, diag::err_enumerator_unnamed_no_def);
2551
2552    // Skip the rest of this declarator, up until the comma or semicolon.
2553    SkipUntil(tok::comma, true);
2554    return;
2555  }
2556
2557  bool Owned = false;
2558  bool IsDependent = false;
2559  const char *PrevSpec = 0;
2560  unsigned DiagID;
2561  Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
2562                                   StartLoc, SS, Name, NameLoc, attrs.getList(),
2563                                   AS,
2564                                   MultiTemplateParamsArg(Actions),
2565                                   Owned, IsDependent, IsScopedEnum,
2566                                   IsScopedUsingClassTag, BaseType);
2567
2568  if (IsDependent) {
2569    // This enum has a dependent nested-name-specifier. Handle it as a
2570    // dependent tag.
2571    if (!Name) {
2572      DS.SetTypeSpecError();
2573      Diag(Tok, diag::err_expected_type_name_after_typename);
2574      return;
2575    }
2576
2577    TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
2578                                                TUK, SS, Name, StartLoc,
2579                                                NameLoc);
2580    if (Type.isInvalid()) {
2581      DS.SetTypeSpecError();
2582      return;
2583    }
2584
2585    if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
2586                           NameLoc.isValid() ? NameLoc : StartLoc,
2587                           PrevSpec, DiagID, Type.get()))
2588      Diag(StartLoc, DiagID) << PrevSpec;
2589
2590    return;
2591  }
2592
2593  if (!TagDecl) {
2594    // The action failed to produce an enumeration tag. If this is a
2595    // definition, consume the entire definition.
2596    if (Tok.is(tok::l_brace)) {
2597      ConsumeBrace();
2598      SkipUntil(tok::r_brace);
2599    }
2600
2601    DS.SetTypeSpecError();
2602    return;
2603  }
2604
2605  if (Tok.is(tok::l_brace))
2606    ParseEnumBody(StartLoc, TagDecl);
2607
2608  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
2609                         NameLoc.isValid() ? NameLoc : StartLoc,
2610                         PrevSpec, DiagID, TagDecl, Owned))
2611    Diag(StartLoc, DiagID) << PrevSpec;
2612}
2613
2614/// ParseEnumBody - Parse a {} enclosed enumerator-list.
2615///       enumerator-list:
2616///         enumerator
2617///         enumerator-list ',' enumerator
2618///       enumerator:
2619///         enumeration-constant
2620///         enumeration-constant '=' constant-expression
2621///       enumeration-constant:
2622///         identifier
2623///
2624void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
2625  // Enter the scope of the enum body and start the definition.
2626  ParseScope EnumScope(this, Scope::DeclScope);
2627  Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
2628
2629  SourceLocation LBraceLoc = ConsumeBrace();
2630
2631  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
2632  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
2633    Diag(Tok, diag::error_empty_enum);
2634
2635  llvm::SmallVector<Decl *, 32> EnumConstantDecls;
2636
2637  Decl *LastEnumConstDecl = 0;
2638
2639  // Parse the enumerator-list.
2640  while (Tok.is(tok::identifier)) {
2641    IdentifierInfo *Ident = Tok.getIdentifierInfo();
2642    SourceLocation IdentLoc = ConsumeToken();
2643
2644    // If attributes exist after the enumerator, parse them.
2645    ParsedAttributes attrs(AttrFactory);
2646    MaybeParseGNUAttributes(attrs);
2647
2648    SourceLocation EqualLoc;
2649    ExprResult AssignedVal;
2650    if (Tok.is(tok::equal)) {
2651      EqualLoc = ConsumeToken();
2652      AssignedVal = ParseConstantExpression();
2653      if (AssignedVal.isInvalid())
2654        SkipUntil(tok::comma, tok::r_brace, true, true);
2655    }
2656
2657    // Install the enumerator constant into EnumDecl.
2658    Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
2659                                                    LastEnumConstDecl,
2660                                                    IdentLoc, Ident,
2661                                                    attrs.getList(), EqualLoc,
2662                                                    AssignedVal.release());
2663    EnumConstantDecls.push_back(EnumConstDecl);
2664    LastEnumConstDecl = EnumConstDecl;
2665
2666    if (Tok.is(tok::identifier)) {
2667      // We're missing a comma between enumerators.
2668      SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2669      Diag(Loc, diag::err_enumerator_list_missing_comma)
2670        << FixItHint::CreateInsertion(Loc, ", ");
2671      continue;
2672    }
2673
2674    if (Tok.isNot(tok::comma))
2675      break;
2676    SourceLocation CommaLoc = ConsumeToken();
2677
2678    if (Tok.isNot(tok::identifier) &&
2679        !(getLang().C99 || getLang().CPlusPlus0x))
2680      Diag(CommaLoc, diag::ext_enumerator_list_comma)
2681        << getLang().CPlusPlus
2682        << FixItHint::CreateRemoval(CommaLoc);
2683  }
2684
2685  // Eat the }.
2686  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2687
2688  // If attributes exist after the identifier list, parse them.
2689  ParsedAttributes attrs(AttrFactory);
2690  MaybeParseGNUAttributes(attrs);
2691
2692  Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
2693                        EnumConstantDecls.data(), EnumConstantDecls.size(),
2694                        getCurScope(), attrs.getList());
2695
2696  EnumScope.Exit();
2697  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, RBraceLoc);
2698}
2699
2700/// isTypeSpecifierQualifier - Return true if the current token could be the
2701/// start of a type-qualifier-list.
2702bool Parser::isTypeQualifier() const {
2703  switch (Tok.getKind()) {
2704  default: return false;
2705
2706    // type-qualifier only in OpenCL
2707  case tok::kw_private:
2708    return getLang().OpenCL;
2709
2710    // type-qualifier
2711  case tok::kw_const:
2712  case tok::kw_volatile:
2713  case tok::kw_restrict:
2714  case tok::kw___private:
2715  case tok::kw___local:
2716  case tok::kw___global:
2717  case tok::kw___constant:
2718  case tok::kw___read_only:
2719  case tok::kw___read_write:
2720  case tok::kw___write_only:
2721    return true;
2722  }
2723}
2724
2725/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2726/// is definitely a type-specifier.  Return false if it isn't part of a type
2727/// specifier or if we're not sure.
2728bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
2729  switch (Tok.getKind()) {
2730  default: return false;
2731    // type-specifiers
2732  case tok::kw_short:
2733  case tok::kw_long:
2734  case tok::kw___int64:
2735  case tok::kw_signed:
2736  case tok::kw_unsigned:
2737  case tok::kw__Complex:
2738  case tok::kw__Imaginary:
2739  case tok::kw_void:
2740  case tok::kw_char:
2741  case tok::kw_wchar_t:
2742  case tok::kw_char16_t:
2743  case tok::kw_char32_t:
2744  case tok::kw_int:
2745  case tok::kw_float:
2746  case tok::kw_double:
2747  case tok::kw_bool:
2748  case tok::kw__Bool:
2749  case tok::kw__Decimal32:
2750  case tok::kw__Decimal64:
2751  case tok::kw__Decimal128:
2752  case tok::kw___vector:
2753
2754    // struct-or-union-specifier (C99) or class-specifier (C++)
2755  case tok::kw_class:
2756  case tok::kw_struct:
2757  case tok::kw_union:
2758    // enum-specifier
2759  case tok::kw_enum:
2760
2761    // typedef-name
2762  case tok::annot_typename:
2763    return true;
2764  }
2765}
2766
2767/// isTypeSpecifierQualifier - Return true if the current token could be the
2768/// start of a specifier-qualifier-list.
2769bool Parser::isTypeSpecifierQualifier() {
2770  switch (Tok.getKind()) {
2771  default: return false;
2772
2773  case tok::identifier:   // foo::bar
2774    if (TryAltiVecVectorToken())
2775      return true;
2776    // Fall through.
2777  case tok::kw_typename:  // typename T::type
2778    // Annotate typenames and C++ scope specifiers.  If we get one, just
2779    // recurse to handle whatever we get.
2780    if (TryAnnotateTypeOrScopeToken())
2781      return true;
2782    if (Tok.is(tok::identifier))
2783      return false;
2784    return isTypeSpecifierQualifier();
2785
2786  case tok::coloncolon:   // ::foo::bar
2787    if (NextToken().is(tok::kw_new) ||    // ::new
2788        NextToken().is(tok::kw_delete))   // ::delete
2789      return false;
2790
2791    if (TryAnnotateTypeOrScopeToken())
2792      return true;
2793    return isTypeSpecifierQualifier();
2794
2795    // GNU attributes support.
2796  case tok::kw___attribute:
2797    // GNU typeof support.
2798  case tok::kw_typeof:
2799
2800    // type-specifiers
2801  case tok::kw_short:
2802  case tok::kw_long:
2803  case tok::kw___int64:
2804  case tok::kw_signed:
2805  case tok::kw_unsigned:
2806  case tok::kw__Complex:
2807  case tok::kw__Imaginary:
2808  case tok::kw_void:
2809  case tok::kw_char:
2810  case tok::kw_wchar_t:
2811  case tok::kw_char16_t:
2812  case tok::kw_char32_t:
2813  case tok::kw_int:
2814  case tok::kw_float:
2815  case tok::kw_double:
2816  case tok::kw_bool:
2817  case tok::kw__Bool:
2818  case tok::kw__Decimal32:
2819  case tok::kw__Decimal64:
2820  case tok::kw__Decimal128:
2821  case tok::kw___vector:
2822
2823    // struct-or-union-specifier (C99) or class-specifier (C++)
2824  case tok::kw_class:
2825  case tok::kw_struct:
2826  case tok::kw_union:
2827    // enum-specifier
2828  case tok::kw_enum:
2829
2830    // type-qualifier
2831  case tok::kw_const:
2832  case tok::kw_volatile:
2833  case tok::kw_restrict:
2834
2835    // typedef-name
2836  case tok::annot_typename:
2837    return true;
2838
2839    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2840  case tok::less:
2841    return getLang().ObjC1;
2842
2843  case tok::kw___cdecl:
2844  case tok::kw___stdcall:
2845  case tok::kw___fastcall:
2846  case tok::kw___thiscall:
2847  case tok::kw___w64:
2848  case tok::kw___ptr64:
2849  case tok::kw___pascal:
2850
2851  case tok::kw___private:
2852  case tok::kw___local:
2853  case tok::kw___global:
2854  case tok::kw___constant:
2855  case tok::kw___read_only:
2856  case tok::kw___read_write:
2857  case tok::kw___write_only:
2858
2859    return true;
2860
2861  case tok::kw_private:
2862    return getLang().OpenCL;
2863  }
2864}
2865
2866/// isDeclarationSpecifier() - Return true if the current token is part of a
2867/// declaration specifier.
2868///
2869/// \param DisambiguatingWithExpression True to indicate that the purpose of
2870/// this check is to disambiguate between an expression and a declaration.
2871bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
2872  switch (Tok.getKind()) {
2873  default: return false;
2874
2875  case tok::kw_private:
2876    return getLang().OpenCL;
2877
2878  case tok::identifier:   // foo::bar
2879    // Unfortunate hack to support "Class.factoryMethod" notation.
2880    if (getLang().ObjC1 && NextToken().is(tok::period))
2881      return false;
2882    if (TryAltiVecVectorToken())
2883      return true;
2884    // Fall through.
2885  case tok::kw_typename: // typename T::type
2886    // Annotate typenames and C++ scope specifiers.  If we get one, just
2887    // recurse to handle whatever we get.
2888    if (TryAnnotateTypeOrScopeToken())
2889      return true;
2890    if (Tok.is(tok::identifier))
2891      return false;
2892
2893    // If we're in Objective-C and we have an Objective-C class type followed
2894    // by an identifier and then either ':' or ']', in a place where an
2895    // expression is permitted, then this is probably a class message send
2896    // missing the initial '['. In this case, we won't consider this to be
2897    // the start of a declaration.
2898    if (DisambiguatingWithExpression &&
2899        isStartOfObjCClassMessageMissingOpenBracket())
2900      return false;
2901
2902    return isDeclarationSpecifier();
2903
2904  case tok::coloncolon:   // ::foo::bar
2905    if (NextToken().is(tok::kw_new) ||    // ::new
2906        NextToken().is(tok::kw_delete))   // ::delete
2907      return false;
2908
2909    // Annotate typenames and C++ scope specifiers.  If we get one, just
2910    // recurse to handle whatever we get.
2911    if (TryAnnotateTypeOrScopeToken())
2912      return true;
2913    return isDeclarationSpecifier();
2914
2915    // storage-class-specifier
2916  case tok::kw_typedef:
2917  case tok::kw_extern:
2918  case tok::kw___private_extern__:
2919  case tok::kw_static:
2920  case tok::kw_auto:
2921  case tok::kw_register:
2922  case tok::kw___thread:
2923
2924    // type-specifiers
2925  case tok::kw_short:
2926  case tok::kw_long:
2927  case tok::kw___int64:
2928  case tok::kw_signed:
2929  case tok::kw_unsigned:
2930  case tok::kw__Complex:
2931  case tok::kw__Imaginary:
2932  case tok::kw_void:
2933  case tok::kw_char:
2934  case tok::kw_wchar_t:
2935  case tok::kw_char16_t:
2936  case tok::kw_char32_t:
2937
2938  case tok::kw_int:
2939  case tok::kw_float:
2940  case tok::kw_double:
2941  case tok::kw_bool:
2942  case tok::kw__Bool:
2943  case tok::kw__Decimal32:
2944  case tok::kw__Decimal64:
2945  case tok::kw__Decimal128:
2946  case tok::kw___vector:
2947
2948    // struct-or-union-specifier (C99) or class-specifier (C++)
2949  case tok::kw_class:
2950  case tok::kw_struct:
2951  case tok::kw_union:
2952    // enum-specifier
2953  case tok::kw_enum:
2954
2955    // type-qualifier
2956  case tok::kw_const:
2957  case tok::kw_volatile:
2958  case tok::kw_restrict:
2959
2960    // function-specifier
2961  case tok::kw_inline:
2962  case tok::kw_virtual:
2963  case tok::kw_explicit:
2964
2965    // static_assert-declaration
2966  case tok::kw__Static_assert:
2967
2968    // GNU typeof support.
2969  case tok::kw_typeof:
2970
2971    // GNU attributes.
2972  case tok::kw___attribute:
2973    return true;
2974
2975    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2976  case tok::less:
2977    return getLang().ObjC1;
2978
2979    // typedef-name
2980  case tok::annot_typename:
2981    return !DisambiguatingWithExpression ||
2982           !isStartOfObjCClassMessageMissingOpenBracket();
2983
2984  case tok::kw___declspec:
2985  case tok::kw___cdecl:
2986  case tok::kw___stdcall:
2987  case tok::kw___fastcall:
2988  case tok::kw___thiscall:
2989  case tok::kw___w64:
2990  case tok::kw___ptr64:
2991  case tok::kw___forceinline:
2992  case tok::kw___pascal:
2993
2994  case tok::kw___private:
2995  case tok::kw___local:
2996  case tok::kw___global:
2997  case tok::kw___constant:
2998  case tok::kw___read_only:
2999  case tok::kw___read_write:
3000  case tok::kw___write_only:
3001
3002    return true;
3003  }
3004}
3005
3006bool Parser::isConstructorDeclarator() {
3007  TentativeParsingAction TPA(*this);
3008
3009  // Parse the C++ scope specifier.
3010  CXXScopeSpec SS;
3011  if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) {
3012    TPA.Revert();
3013    return false;
3014  }
3015
3016  // Parse the constructor name.
3017  if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
3018    // We already know that we have a constructor name; just consume
3019    // the token.
3020    ConsumeToken();
3021  } else {
3022    TPA.Revert();
3023    return false;
3024  }
3025
3026  // Current class name must be followed by a left parentheses.
3027  if (Tok.isNot(tok::l_paren)) {
3028    TPA.Revert();
3029    return false;
3030  }
3031  ConsumeParen();
3032
3033  // A right parentheses or ellipsis signals that we have a constructor.
3034  if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
3035    TPA.Revert();
3036    return true;
3037  }
3038
3039  // If we need to, enter the specified scope.
3040  DeclaratorScopeObj DeclScopeObj(*this, SS);
3041  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3042    DeclScopeObj.EnterDeclaratorScope();
3043
3044  // Optionally skip Microsoft attributes.
3045  ParsedAttributes Attrs(AttrFactory);
3046  MaybeParseMicrosoftAttributes(Attrs);
3047
3048  // Check whether the next token(s) are part of a declaration
3049  // specifier, in which case we have the start of a parameter and,
3050  // therefore, we know that this is a constructor.
3051  bool IsConstructor = isDeclarationSpecifier();
3052  TPA.Revert();
3053  return IsConstructor;
3054}
3055
3056/// ParseTypeQualifierListOpt
3057///          type-qualifier-list: [C99 6.7.5]
3058///            type-qualifier
3059/// [vendor]   attributes
3060///              [ only if VendorAttributesAllowed=true ]
3061///            type-qualifier-list type-qualifier
3062/// [vendor]   type-qualifier-list attributes
3063///              [ only if VendorAttributesAllowed=true ]
3064/// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
3065///              [ only if CXX0XAttributesAllowed=true ]
3066/// Note: vendor can be GNU, MS, etc.
3067///
3068void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
3069                                       bool VendorAttributesAllowed,
3070                                       bool CXX0XAttributesAllowed) {
3071  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3072    SourceLocation Loc = Tok.getLocation();
3073    ParsedAttributesWithRange attrs(AttrFactory);
3074    ParseCXX0XAttributes(attrs);
3075    if (CXX0XAttributesAllowed)
3076      DS.takeAttributesFrom(attrs);
3077    else
3078      Diag(Loc, diag::err_attributes_not_allowed);
3079  }
3080
3081  SourceLocation EndLoc;
3082
3083  while (1) {
3084    bool isInvalid = false;
3085    const char *PrevSpec = 0;
3086    unsigned DiagID = 0;
3087    SourceLocation Loc = Tok.getLocation();
3088
3089    switch (Tok.getKind()) {
3090    case tok::code_completion:
3091      Actions.CodeCompleteTypeQualifiers(DS);
3092      ConsumeCodeCompletionToken();
3093      break;
3094
3095    case tok::kw_const:
3096      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
3097                                 getLang());
3098      break;
3099    case tok::kw_volatile:
3100      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3101                                 getLang());
3102      break;
3103    case tok::kw_restrict:
3104      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3105                                 getLang());
3106      break;
3107
3108    // OpenCL qualifiers:
3109    case tok::kw_private:
3110      if (!getLang().OpenCL)
3111        goto DoneWithTypeQuals;
3112    case tok::kw___private:
3113    case tok::kw___global:
3114    case tok::kw___local:
3115    case tok::kw___constant:
3116    case tok::kw___read_only:
3117    case tok::kw___write_only:
3118    case tok::kw___read_write:
3119      ParseOpenCLQualifiers(DS);
3120      break;
3121
3122    case tok::kw___w64:
3123    case tok::kw___ptr64:
3124    case tok::kw___cdecl:
3125    case tok::kw___stdcall:
3126    case tok::kw___fastcall:
3127    case tok::kw___thiscall:
3128      if (VendorAttributesAllowed) {
3129        ParseMicrosoftTypeAttributes(DS.getAttributes());
3130        continue;
3131      }
3132      goto DoneWithTypeQuals;
3133    case tok::kw___pascal:
3134      if (VendorAttributesAllowed) {
3135        ParseBorlandTypeAttributes(DS.getAttributes());
3136        continue;
3137      }
3138      goto DoneWithTypeQuals;
3139    case tok::kw___attribute:
3140      if (VendorAttributesAllowed) {
3141        ParseGNUAttributes(DS.getAttributes());
3142        continue; // do *not* consume the next token!
3143      }
3144      // otherwise, FALL THROUGH!
3145    default:
3146      DoneWithTypeQuals:
3147      // If this is not a type-qualifier token, we're done reading type
3148      // qualifiers.  First verify that DeclSpec's are consistent.
3149      DS.Finish(Diags, PP);
3150      if (EndLoc.isValid())
3151        DS.SetRangeEnd(EndLoc);
3152      return;
3153    }
3154
3155    // If the specifier combination wasn't legal, issue a diagnostic.
3156    if (isInvalid) {
3157      assert(PrevSpec && "Method did not return previous specifier!");
3158      Diag(Tok, DiagID) << PrevSpec;
3159    }
3160    EndLoc = ConsumeToken();
3161  }
3162}
3163
3164
3165/// ParseDeclarator - Parse and verify a newly-initialized declarator.
3166///
3167void Parser::ParseDeclarator(Declarator &D) {
3168  /// This implements the 'declarator' production in the C grammar, then checks
3169  /// for well-formedness and issues diagnostics.
3170  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3171}
3172
3173/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
3174/// is parsed by the function passed to it. Pass null, and the direct-declarator
3175/// isn't parsed at all, making this function effectively parse the C++
3176/// ptr-operator production.
3177///
3178///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
3179/// [C]     pointer[opt] direct-declarator
3180/// [C++]   direct-declarator
3181/// [C++]   ptr-operator declarator
3182///
3183///       pointer: [C99 6.7.5]
3184///         '*' type-qualifier-list[opt]
3185///         '*' type-qualifier-list[opt] pointer
3186///
3187///       ptr-operator:
3188///         '*' cv-qualifier-seq[opt]
3189///         '&'
3190/// [C++0x] '&&'
3191/// [GNU]   '&' restrict[opt] attributes[opt]
3192/// [GNU?]  '&&' restrict[opt] attributes[opt]
3193///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
3194void Parser::ParseDeclaratorInternal(Declarator &D,
3195                                     DirectDeclParseFunction DirectDeclParser) {
3196  if (Diags.hasAllExtensionsSilenced())
3197    D.setExtension();
3198
3199  // C++ member pointers start with a '::' or a nested-name.
3200  // Member pointers get special handling, since there's no place for the
3201  // scope spec in the generic path below.
3202  if (getLang().CPlusPlus &&
3203      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
3204       Tok.is(tok::annot_cxxscope))) {
3205    CXXScopeSpec SS;
3206    ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true); // ignore fail
3207
3208    if (SS.isNotEmpty()) {
3209      if (Tok.isNot(tok::star)) {
3210        // The scope spec really belongs to the direct-declarator.
3211        D.getCXXScopeSpec() = SS;
3212        if (DirectDeclParser)
3213          (this->*DirectDeclParser)(D);
3214        return;
3215      }
3216
3217      SourceLocation Loc = ConsumeToken();
3218      D.SetRangeEnd(Loc);
3219      DeclSpec DS(AttrFactory);
3220      ParseTypeQualifierListOpt(DS);
3221      D.ExtendWithDeclSpec(DS);
3222
3223      // Recurse to parse whatever is left.
3224      ParseDeclaratorInternal(D, DirectDeclParser);
3225
3226      // Sema will have to catch (syntactically invalid) pointers into global
3227      // scope. It has to catch pointers into namespace scope anyway.
3228      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
3229                                                      Loc),
3230                    DS.getAttributes(),
3231                    /* Don't replace range end. */SourceLocation());
3232      return;
3233    }
3234  }
3235
3236  tok::TokenKind Kind = Tok.getKind();
3237  // Not a pointer, C++ reference, or block.
3238  if (Kind != tok::star && Kind != tok::caret &&
3239      (Kind != tok::amp || !getLang().CPlusPlus) &&
3240      // We parse rvalue refs in C++03, because otherwise the errors are scary.
3241      (Kind != tok::ampamp || !getLang().CPlusPlus)) {
3242    if (DirectDeclParser)
3243      (this->*DirectDeclParser)(D);
3244    return;
3245  }
3246
3247  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
3248  // '&&' -> rvalue reference
3249  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
3250  D.SetRangeEnd(Loc);
3251
3252  if (Kind == tok::star || Kind == tok::caret) {
3253    // Is a pointer.
3254    DeclSpec DS(AttrFactory);
3255
3256    ParseTypeQualifierListOpt(DS);
3257    D.ExtendWithDeclSpec(DS);
3258
3259    // Recursively parse the declarator.
3260    ParseDeclaratorInternal(D, DirectDeclParser);
3261    if (Kind == tok::star)
3262      // Remember that we parsed a pointer type, and remember the type-quals.
3263      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
3264                                                DS.getConstSpecLoc(),
3265                                                DS.getVolatileSpecLoc(),
3266                                                DS.getRestrictSpecLoc()),
3267                    DS.getAttributes(),
3268                    SourceLocation());
3269    else
3270      // Remember that we parsed a Block type, and remember the type-quals.
3271      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
3272                                                     Loc),
3273                    DS.getAttributes(),
3274                    SourceLocation());
3275  } else {
3276    // Is a reference
3277    DeclSpec DS(AttrFactory);
3278
3279    // Complain about rvalue references in C++03, but then go on and build
3280    // the declarator.
3281    if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
3282      Diag(Loc, diag::ext_rvalue_reference);
3283
3284    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
3285    // cv-qualifiers are introduced through the use of a typedef or of a
3286    // template type argument, in which case the cv-qualifiers are ignored.
3287    //
3288    // [GNU] Retricted references are allowed.
3289    // [GNU] Attributes on references are allowed.
3290    // [C++0x] Attributes on references are not allowed.
3291    ParseTypeQualifierListOpt(DS, true, false);
3292    D.ExtendWithDeclSpec(DS);
3293
3294    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
3295      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3296        Diag(DS.getConstSpecLoc(),
3297             diag::err_invalid_reference_qualifier_application) << "const";
3298      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3299        Diag(DS.getVolatileSpecLoc(),
3300             diag::err_invalid_reference_qualifier_application) << "volatile";
3301    }
3302
3303    // Recursively parse the declarator.
3304    ParseDeclaratorInternal(D, DirectDeclParser);
3305
3306    if (D.getNumTypeObjects() > 0) {
3307      // C++ [dcl.ref]p4: There shall be no references to references.
3308      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
3309      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
3310        if (const IdentifierInfo *II = D.getIdentifier())
3311          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3312           << II;
3313        else
3314          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3315            << "type name";
3316
3317        // Once we've complained about the reference-to-reference, we
3318        // can go ahead and build the (technically ill-formed)
3319        // declarator: reference collapsing will take care of it.
3320      }
3321    }
3322
3323    // Remember that we parsed a reference type. It doesn't have type-quals.
3324    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
3325                                                Kind == tok::amp),
3326                  DS.getAttributes(),
3327                  SourceLocation());
3328  }
3329}
3330
3331/// ParseDirectDeclarator
3332///       direct-declarator: [C99 6.7.5]
3333/// [C99]   identifier
3334///         '(' declarator ')'
3335/// [GNU]   '(' attributes declarator ')'
3336/// [C90]   direct-declarator '[' constant-expression[opt] ']'
3337/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3338/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3339/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3340/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
3341///         direct-declarator '(' parameter-type-list ')'
3342///         direct-declarator '(' identifier-list[opt] ')'
3343/// [GNU]   direct-declarator '(' parameter-forward-declarations
3344///                    parameter-type-list[opt] ')'
3345/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
3346///                    cv-qualifier-seq[opt] exception-specification[opt]
3347/// [C++]   declarator-id
3348///
3349///       declarator-id: [C++ 8]
3350///         '...'[opt] id-expression
3351///         '::'[opt] nested-name-specifier[opt] type-name
3352///
3353///       id-expression: [C++ 5.1]
3354///         unqualified-id
3355///         qualified-id
3356///
3357///       unqualified-id: [C++ 5.1]
3358///         identifier
3359///         operator-function-id
3360///         conversion-function-id
3361///          '~' class-name
3362///         template-id
3363///
3364void Parser::ParseDirectDeclarator(Declarator &D) {
3365  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
3366
3367  if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
3368    // ParseDeclaratorInternal might already have parsed the scope.
3369    if (D.getCXXScopeSpec().isEmpty()) {
3370      ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), true);
3371    }
3372
3373    if (D.getCXXScopeSpec().isValid()) {
3374      if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3375        // Change the declaration context for name lookup, until this function
3376        // is exited (and the declarator has been parsed).
3377        DeclScopeObj.EnterDeclaratorScope();
3378    }
3379
3380    // C++0x [dcl.fct]p14:
3381    //   There is a syntactic ambiguity when an ellipsis occurs at the end
3382    //   of a parameter-declaration-clause without a preceding comma. In
3383    //   this case, the ellipsis is parsed as part of the
3384    //   abstract-declarator if the type of the parameter names a template
3385    //   parameter pack that has not been expanded; otherwise, it is parsed
3386    //   as part of the parameter-declaration-clause.
3387    if (Tok.is(tok::ellipsis) &&
3388        !((D.getContext() == Declarator::PrototypeContext ||
3389           D.getContext() == Declarator::BlockLiteralContext) &&
3390          NextToken().is(tok::r_paren) &&
3391          !Actions.containsUnexpandedParameterPacks(D)))
3392      D.setEllipsisLoc(ConsumeToken());
3393
3394    if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
3395        Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
3396      // We found something that indicates the start of an unqualified-id.
3397      // Parse that unqualified-id.
3398      bool AllowConstructorName;
3399      if (D.getDeclSpec().hasTypeSpecifier())
3400        AllowConstructorName = false;
3401      else if (D.getCXXScopeSpec().isSet())
3402        AllowConstructorName =
3403          (D.getContext() == Declarator::FileContext ||
3404           (D.getContext() == Declarator::MemberContext &&
3405            D.getDeclSpec().isFriendSpecified()));
3406      else
3407        AllowConstructorName = (D.getContext() == Declarator::MemberContext);
3408
3409      if (ParseUnqualifiedId(D.getCXXScopeSpec(),
3410                             /*EnteringContext=*/true,
3411                             /*AllowDestructorName=*/true,
3412                             AllowConstructorName,
3413                             ParsedType(),
3414                             D.getName()) ||
3415          // Once we're past the identifier, if the scope was bad, mark the
3416          // whole declarator bad.
3417          D.getCXXScopeSpec().isInvalid()) {
3418        D.SetIdentifier(0, Tok.getLocation());
3419        D.setInvalidType(true);
3420      } else {
3421        // Parsed the unqualified-id; update range information and move along.
3422        if (D.getSourceRange().getBegin().isInvalid())
3423          D.SetRangeBegin(D.getName().getSourceRange().getBegin());
3424        D.SetRangeEnd(D.getName().getSourceRange().getEnd());
3425      }
3426      goto PastIdentifier;
3427    }
3428  } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
3429    assert(!getLang().CPlusPlus &&
3430           "There's a C++-specific check for tok::identifier above");
3431    assert(Tok.getIdentifierInfo() && "Not an identifier?");
3432    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
3433    ConsumeToken();
3434    goto PastIdentifier;
3435  }
3436
3437  if (Tok.is(tok::l_paren)) {
3438    // direct-declarator: '(' declarator ')'
3439    // direct-declarator: '(' attributes declarator ')'
3440    // Example: 'char (*X)'   or 'int (*XX)(void)'
3441    ParseParenDeclarator(D);
3442
3443    // If the declarator was parenthesized, we entered the declarator
3444    // scope when parsing the parenthesized declarator, then exited
3445    // the scope already. Re-enter the scope, if we need to.
3446    if (D.getCXXScopeSpec().isSet()) {
3447      // If there was an error parsing parenthesized declarator, declarator
3448      // scope may have been enterred before. Don't do it again.
3449      if (!D.isInvalidType() &&
3450          Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3451        // Change the declaration context for name lookup, until this function
3452        // is exited (and the declarator has been parsed).
3453        DeclScopeObj.EnterDeclaratorScope();
3454    }
3455  } else if (D.mayOmitIdentifier()) {
3456    // This could be something simple like "int" (in which case the declarator
3457    // portion is empty), if an abstract-declarator is allowed.
3458    D.SetIdentifier(0, Tok.getLocation());
3459  } else {
3460    if (D.getContext() == Declarator::MemberContext)
3461      Diag(Tok, diag::err_expected_member_name_or_semi)
3462        << D.getDeclSpec().getSourceRange();
3463    else if (getLang().CPlusPlus)
3464      Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
3465    else
3466      Diag(Tok, diag::err_expected_ident_lparen);
3467    D.SetIdentifier(0, Tok.getLocation());
3468    D.setInvalidType(true);
3469  }
3470
3471 PastIdentifier:
3472  assert(D.isPastIdentifier() &&
3473         "Haven't past the location of the identifier yet?");
3474
3475  // Don't parse attributes unless we have an identifier.
3476  if (D.getIdentifier())
3477    MaybeParseCXX0XAttributes(D);
3478
3479  while (1) {
3480    if (Tok.is(tok::l_paren)) {
3481      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
3482      // In such a case, check if we actually have a function declarator; if it
3483      // is not, the declarator has been fully parsed.
3484      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
3485        // When not in file scope, warn for ambiguous function declarators, just
3486        // in case the author intended it as a variable definition.
3487        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
3488        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
3489          break;
3490      }
3491      ParsedAttributes attrs(AttrFactory);
3492      ParseFunctionDeclarator(ConsumeParen(), D, attrs);
3493    } else if (Tok.is(tok::l_square)) {
3494      ParseBracketDeclarator(D);
3495    } else {
3496      break;
3497    }
3498  }
3499}
3500
3501/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
3502/// only called before the identifier, so these are most likely just grouping
3503/// parens for precedence.  If we find that these are actually function
3504/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
3505///
3506///       direct-declarator:
3507///         '(' declarator ')'
3508/// [GNU]   '(' attributes declarator ')'
3509///         direct-declarator '(' parameter-type-list ')'
3510///         direct-declarator '(' identifier-list[opt] ')'
3511/// [GNU]   direct-declarator '(' parameter-forward-declarations
3512///                    parameter-type-list[opt] ')'
3513///
3514void Parser::ParseParenDeclarator(Declarator &D) {
3515  SourceLocation StartLoc = ConsumeParen();
3516  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
3517
3518  // Eat any attributes before we look at whether this is a grouping or function
3519  // declarator paren.  If this is a grouping paren, the attribute applies to
3520  // the type being built up, for example:
3521  //     int (__attribute__(()) *x)(long y)
3522  // If this ends up not being a grouping paren, the attribute applies to the
3523  // first argument, for example:
3524  //     int (__attribute__(()) int x)
3525  // In either case, we need to eat any attributes to be able to determine what
3526  // sort of paren this is.
3527  //
3528  ParsedAttributes attrs(AttrFactory);
3529  bool RequiresArg = false;
3530  if (Tok.is(tok::kw___attribute)) {
3531    ParseGNUAttributes(attrs);
3532
3533    // We require that the argument list (if this is a non-grouping paren) be
3534    // present even if the attribute list was empty.
3535    RequiresArg = true;
3536  }
3537  // Eat any Microsoft extensions.
3538  if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
3539       Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
3540       Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64)) {
3541    ParseMicrosoftTypeAttributes(attrs);
3542  }
3543  // Eat any Borland extensions.
3544  if  (Tok.is(tok::kw___pascal))
3545    ParseBorlandTypeAttributes(attrs);
3546
3547  // If we haven't past the identifier yet (or where the identifier would be
3548  // stored, if this is an abstract declarator), then this is probably just
3549  // grouping parens. However, if this could be an abstract-declarator, then
3550  // this could also be the start of function arguments (consider 'void()').
3551  bool isGrouping;
3552
3553  if (!D.mayOmitIdentifier()) {
3554    // If this can't be an abstract-declarator, this *must* be a grouping
3555    // paren, because we haven't seen the identifier yet.
3556    isGrouping = true;
3557  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
3558             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
3559             isDeclarationSpecifier()) {       // 'int(int)' is a function.
3560    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
3561    // considered to be a type, not a K&R identifier-list.
3562    isGrouping = false;
3563  } else {
3564    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
3565    isGrouping = true;
3566  }
3567
3568  // If this is a grouping paren, handle:
3569  // direct-declarator: '(' declarator ')'
3570  // direct-declarator: '(' attributes declarator ')'
3571  if (isGrouping) {
3572    bool hadGroupingParens = D.hasGroupingParens();
3573    D.setGroupingParens(true);
3574
3575    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3576    // Match the ')'.
3577    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, StartLoc);
3578    D.AddTypeInfo(DeclaratorChunk::getParen(StartLoc, EndLoc),
3579                  attrs, EndLoc);
3580
3581    D.setGroupingParens(hadGroupingParens);
3582    return;
3583  }
3584
3585  // Okay, if this wasn't a grouping paren, it must be the start of a function
3586  // argument list.  Recognize that this declarator will never have an
3587  // identifier (and remember where it would have been), then call into
3588  // ParseFunctionDeclarator to handle of argument list.
3589  D.SetIdentifier(0, Tok.getLocation());
3590
3591  ParseFunctionDeclarator(StartLoc, D, attrs, RequiresArg);
3592}
3593
3594/// ParseFunctionDeclarator - We are after the identifier and have parsed the
3595/// declarator D up to a paren, which indicates that we are parsing function
3596/// arguments.
3597///
3598/// If AttrList is non-null, then the caller parsed those arguments immediately
3599/// after the open paren - they should be considered to be the first argument of
3600/// a parameter.  If RequiresArg is true, then the first argument of the
3601/// function is required to be present and required to not be an identifier
3602/// list.
3603///
3604/// This method also handles this portion of the grammar:
3605///       parameter-type-list: [C99 6.7.5]
3606///         parameter-list
3607///         parameter-list ',' '...'
3608/// [C++]   parameter-list '...'
3609///
3610///       parameter-list: [C99 6.7.5]
3611///         parameter-declaration
3612///         parameter-list ',' parameter-declaration
3613///
3614///       parameter-declaration: [C99 6.7.5]
3615///         declaration-specifiers declarator
3616/// [C++]   declaration-specifiers declarator '=' assignment-expression
3617/// [GNU]   declaration-specifiers declarator attributes
3618///         declaration-specifiers abstract-declarator[opt]
3619/// [C++]   declaration-specifiers abstract-declarator[opt]
3620///           '=' assignment-expression
3621/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
3622///
3623/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]",
3624/// C++0x "ref-qualifier[opt]" and "exception-specification[opt]".
3625///
3626/// [C++0x] exception-specification:
3627///           dynamic-exception-specification
3628///           noexcept-specification
3629///
3630void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
3631                                     ParsedAttributes &attrs,
3632                                     bool RequiresArg) {
3633  // lparen is already consumed!
3634  assert(D.isPastIdentifier() && "Should not call before identifier!");
3635
3636  ParsedType TrailingReturnType;
3637
3638  // This parameter list may be empty.
3639  if (Tok.is(tok::r_paren)) {
3640    if (RequiresArg)
3641      Diag(Tok, diag::err_argument_required_after_attribute);
3642
3643    SourceLocation EndLoc = ConsumeParen();  // Eat the closing ')'.
3644
3645    // cv-qualifier-seq[opt].
3646    DeclSpec DS(AttrFactory);
3647    SourceLocation RefQualifierLoc;
3648    bool RefQualifierIsLValueRef = true;
3649    ExceptionSpecificationType ESpecType = EST_None;
3650    SourceRange ESpecRange;
3651    llvm::SmallVector<ParsedType, 2> DynamicExceptions;
3652    llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
3653    ExprResult NoexceptExpr;
3654    if (getLang().CPlusPlus) {
3655      MaybeParseCXX0XAttributes(attrs);
3656
3657      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3658      if (!DS.getSourceRange().getEnd().isInvalid())
3659        EndLoc = DS.getSourceRange().getEnd();
3660
3661      // Parse ref-qualifier[opt]
3662      if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
3663        if (!getLang().CPlusPlus0x)
3664          Diag(Tok, diag::ext_ref_qualifier);
3665
3666        RefQualifierIsLValueRef = Tok.is(tok::amp);
3667        RefQualifierLoc = ConsumeToken();
3668        EndLoc = RefQualifierLoc;
3669      }
3670
3671      // Parse exception-specification[opt].
3672      ESpecType = MaybeParseExceptionSpecification(ESpecRange,
3673                                                   DynamicExceptions,
3674                                                   DynamicExceptionRanges,
3675                                                   NoexceptExpr);
3676      if (ESpecType != EST_None)
3677        EndLoc = ESpecRange.getEnd();
3678
3679      // Parse trailing-return-type.
3680      if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
3681        TrailingReturnType = ParseTrailingReturnType().get();
3682      }
3683    }
3684
3685    // Remember that we parsed a function type, and remember the attributes.
3686    // int() -> no prototype, no '...'.
3687    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
3688                                               /*variadic*/ false,
3689                                               SourceLocation(),
3690                                               /*arglist*/ 0, 0,
3691                                               DS.getTypeQualifiers(),
3692                                               RefQualifierIsLValueRef,
3693                                               RefQualifierLoc,
3694                                               ESpecType, ESpecRange.getBegin(),
3695                                               DynamicExceptions.data(),
3696                                               DynamicExceptionRanges.data(),
3697                                               DynamicExceptions.size(),
3698                                               NoexceptExpr.isUsable() ?
3699                                                 NoexceptExpr.get() : 0,
3700                                               LParenLoc, EndLoc, D,
3701                                               TrailingReturnType),
3702                  attrs, EndLoc);
3703    return;
3704  }
3705
3706  // Alternatively, this parameter list may be an identifier list form for a
3707  // K&R-style function:  void foo(a,b,c)
3708  if (!getLang().CPlusPlus && Tok.is(tok::identifier)
3709      && !TryAltiVecVectorToken()) {
3710    if (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) {
3711      // K&R identifier lists can't have typedefs as identifiers, per
3712      // C99 6.7.5.3p11.
3713      if (RequiresArg)
3714        Diag(Tok, diag::err_argument_required_after_attribute);
3715
3716      // Identifier list.  Note that '(' identifier-list ')' is only allowed for
3717      // normal declarators, not for abstract-declarators.  Get the first
3718      // identifier.
3719      Token FirstTok = Tok;
3720      ConsumeToken();  // eat the first identifier.
3721
3722      // Identifier lists follow a really simple grammar: the identifiers can
3723      // be followed *only* by a ", moreidentifiers" or ")".  However, K&R
3724      // identifier lists are really rare in the brave new modern world, and it
3725      // is very common for someone to typo a type in a non-k&r style list.  If
3726      // we are presented with something like: "void foo(intptr x, float y)",
3727      // we don't want to start parsing the function declarator as though it is
3728      // a K&R style declarator just because intptr is an invalid type.
3729      //
3730      // To handle this, we check to see if the token after the first identifier
3731      // is a "," or ")".  Only if so, do we parse it as an identifier list.
3732      if (Tok.is(tok::comma) || Tok.is(tok::r_paren))
3733        return ParseFunctionDeclaratorIdentifierList(LParenLoc,
3734                                                   FirstTok.getIdentifierInfo(),
3735                                                     FirstTok.getLocation(), D);
3736
3737      // If we get here, the code is invalid.  Push the first identifier back
3738      // into the token stream and parse the first argument as an (invalid)
3739      // normal argument declarator.
3740      PP.EnterToken(Tok);
3741      Tok = FirstTok;
3742    }
3743  }
3744
3745  // Finally, a normal, non-empty parameter type list.
3746
3747  // Build up an array of information about the parsed arguments.
3748  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3749
3750  // Enter function-declaration scope, limiting any declarators to the
3751  // function prototype scope, including parameter declarators.
3752  ParseScope PrototypeScope(this,
3753                            Scope::FunctionPrototypeScope|Scope::DeclScope);
3754
3755  bool IsVariadic = false;
3756  SourceLocation EllipsisLoc;
3757  while (1) {
3758    if (Tok.is(tok::ellipsis)) {
3759      IsVariadic = true;
3760      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
3761      break;
3762    }
3763
3764    // Parse the declaration-specifiers.
3765    // Just use the ParsingDeclaration "scope" of the declarator.
3766    DeclSpec DS(AttrFactory);
3767
3768    // Skip any Microsoft attributes before a param.
3769    if (getLang().Microsoft && Tok.is(tok::l_square))
3770      ParseMicrosoftAttributes(DS.getAttributes());
3771
3772    SourceLocation DSStart = Tok.getLocation();
3773
3774    // If the caller parsed attributes for the first argument, add them now.
3775    // Take them so that we only apply the attributes to the first parameter.
3776    DS.takeAttributesFrom(attrs);
3777
3778    ParseDeclarationSpecifiers(DS);
3779
3780    // Parse the declarator.  This is "PrototypeContext", because we must
3781    // accept either 'declarator' or 'abstract-declarator' here.
3782    Declarator ParmDecl(DS, Declarator::PrototypeContext);
3783    ParseDeclarator(ParmDecl);
3784
3785    // Parse GNU attributes, if present.
3786    MaybeParseGNUAttributes(ParmDecl);
3787
3788    // Remember this parsed parameter in ParamInfo.
3789    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
3790
3791    // DefArgToks is used when the parsing of default arguments needs
3792    // to be delayed.
3793    CachedTokens *DefArgToks = 0;
3794
3795    // If no parameter was specified, verify that *something* was specified,
3796    // otherwise we have a missing type and identifier.
3797    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
3798        ParmDecl.getNumTypeObjects() == 0) {
3799      // Completely missing, emit error.
3800      Diag(DSStart, diag::err_missing_param);
3801    } else {
3802      // Otherwise, we have something.  Add it and let semantic analysis try
3803      // to grok it and add the result to the ParamInfo we are building.
3804
3805      // Inform the actions module about the parameter declarator, so it gets
3806      // added to the current scope.
3807      Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
3808
3809      // Parse the default argument, if any. We parse the default
3810      // arguments in all dialects; the semantic analysis in
3811      // ActOnParamDefaultArgument will reject the default argument in
3812      // C.
3813      if (Tok.is(tok::equal)) {
3814        SourceLocation EqualLoc = Tok.getLocation();
3815
3816        // Parse the default argument
3817        if (D.getContext() == Declarator::MemberContext) {
3818          // If we're inside a class definition, cache the tokens
3819          // corresponding to the default argument. We'll actually parse
3820          // them when we see the end of the class definition.
3821          // FIXME: Templates will require something similar.
3822          // FIXME: Can we use a smart pointer for Toks?
3823          DefArgToks = new CachedTokens;
3824
3825          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
3826                                    /*StopAtSemi=*/true,
3827                                    /*ConsumeFinalToken=*/false)) {
3828            delete DefArgToks;
3829            DefArgToks = 0;
3830            Actions.ActOnParamDefaultArgumentError(Param);
3831          } else {
3832            // Mark the end of the default argument so that we know when to
3833            // stop when we parse it later on.
3834            Token DefArgEnd;
3835            DefArgEnd.startToken();
3836            DefArgEnd.setKind(tok::cxx_defaultarg_end);
3837            DefArgEnd.setLocation(Tok.getLocation());
3838            DefArgToks->push_back(DefArgEnd);
3839            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
3840                                                (*DefArgToks)[1].getLocation());
3841          }
3842        } else {
3843          // Consume the '='.
3844          ConsumeToken();
3845
3846          // The argument isn't actually potentially evaluated unless it is
3847          // used.
3848          EnterExpressionEvaluationContext Eval(Actions,
3849                                              Sema::PotentiallyEvaluatedIfUsed);
3850
3851          ExprResult DefArgResult(ParseAssignmentExpression());
3852          if (DefArgResult.isInvalid()) {
3853            Actions.ActOnParamDefaultArgumentError(Param);
3854            SkipUntil(tok::comma, tok::r_paren, true, true);
3855          } else {
3856            // Inform the actions module about the default argument
3857            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
3858                                              DefArgResult.take());
3859          }
3860        }
3861      }
3862
3863      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3864                                          ParmDecl.getIdentifierLoc(), Param,
3865                                          DefArgToks));
3866    }
3867
3868    // If the next token is a comma, consume it and keep reading arguments.
3869    if (Tok.isNot(tok::comma)) {
3870      if (Tok.is(tok::ellipsis)) {
3871        IsVariadic = true;
3872        EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
3873
3874        if (!getLang().CPlusPlus) {
3875          // We have ellipsis without a preceding ',', which is ill-formed
3876          // in C. Complain and provide the fix.
3877          Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
3878            << FixItHint::CreateInsertion(EllipsisLoc, ", ");
3879        }
3880      }
3881
3882      break;
3883    }
3884
3885    // Consume the comma.
3886    ConsumeToken();
3887  }
3888
3889  // If we have the closing ')', eat it.
3890  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3891
3892  DeclSpec DS(AttrFactory);
3893  SourceLocation RefQualifierLoc;
3894  bool RefQualifierIsLValueRef = true;
3895  ExceptionSpecificationType ESpecType = EST_None;
3896  SourceRange ESpecRange;
3897  llvm::SmallVector<ParsedType, 2> DynamicExceptions;
3898  llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
3899  ExprResult NoexceptExpr;
3900
3901  if (getLang().CPlusPlus) {
3902    MaybeParseCXX0XAttributes(attrs);
3903
3904    // Parse cv-qualifier-seq[opt].
3905    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3906      if (!DS.getSourceRange().getEnd().isInvalid())
3907        EndLoc = DS.getSourceRange().getEnd();
3908
3909    // Parse ref-qualifier[opt]
3910    if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
3911      if (!getLang().CPlusPlus0x)
3912        Diag(Tok, diag::ext_ref_qualifier);
3913
3914      RefQualifierIsLValueRef = Tok.is(tok::amp);
3915      RefQualifierLoc = ConsumeToken();
3916      EndLoc = RefQualifierLoc;
3917    }
3918
3919    // FIXME: We should leave the prototype scope before parsing the exception
3920    // specification, and then reenter it when parsing the trailing return type.
3921    // FIXMEFIXME: Why? That wouldn't be right for the noexcept clause.
3922
3923    // Parse exception-specification[opt].
3924    ESpecType = MaybeParseExceptionSpecification(ESpecRange,
3925                                                 DynamicExceptions,
3926                                                 DynamicExceptionRanges,
3927                                                 NoexceptExpr);
3928    if (ESpecType != EST_None)
3929      EndLoc = ESpecRange.getEnd();
3930
3931    // Parse trailing-return-type.
3932    if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
3933      TrailingReturnType = ParseTrailingReturnType().get();
3934    }
3935  }
3936
3937  // Leave prototype scope.
3938  PrototypeScope.Exit();
3939
3940  // Remember that we parsed a function type, and remember the attributes.
3941  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
3942                                             EllipsisLoc,
3943                                             ParamInfo.data(), ParamInfo.size(),
3944                                             DS.getTypeQualifiers(),
3945                                             RefQualifierIsLValueRef,
3946                                             RefQualifierLoc,
3947                                             ESpecType, ESpecRange.getBegin(),
3948                                             DynamicExceptions.data(),
3949                                             DynamicExceptionRanges.data(),
3950                                             DynamicExceptions.size(),
3951                                             NoexceptExpr.isUsable() ?
3952                                               NoexceptExpr.get() : 0,
3953                                             LParenLoc, EndLoc, D,
3954                                             TrailingReturnType),
3955                attrs, EndLoc);
3956}
3957
3958/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
3959/// we found a K&R-style identifier list instead of a type argument list.  The
3960/// first identifier has already been consumed, and the current token is the
3961/// token right after it.
3962///
3963///       identifier-list: [C99 6.7.5]
3964///         identifier
3965///         identifier-list ',' identifier
3966///
3967void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
3968                                                   IdentifierInfo *FirstIdent,
3969                                                   SourceLocation FirstIdentLoc,
3970                                                   Declarator &D) {
3971  // Build up an array of information about the parsed arguments.
3972  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3973  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
3974
3975  // If there was no identifier specified for the declarator, either we are in
3976  // an abstract-declarator, or we are in a parameter declarator which was found
3977  // to be abstract.  In abstract-declarators, identifier lists are not valid:
3978  // diagnose this.
3979  if (!D.getIdentifier())
3980    Diag(FirstIdentLoc, diag::ext_ident_list_in_param);
3981
3982  // The first identifier was already read, and is known to be the first
3983  // identifier in the list.  Remember this identifier in ParamInfo.
3984  ParamsSoFar.insert(FirstIdent);
3985  ParamInfo.push_back(DeclaratorChunk::ParamInfo(FirstIdent, FirstIdentLoc, 0));
3986
3987  while (Tok.is(tok::comma)) {
3988    // Eat the comma.
3989    ConsumeToken();
3990
3991    // If this isn't an identifier, report the error and skip until ')'.
3992    if (Tok.isNot(tok::identifier)) {
3993      Diag(Tok, diag::err_expected_ident);
3994      SkipUntil(tok::r_paren);
3995      return;
3996    }
3997
3998    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
3999
4000    // Reject 'typedef int y; int test(x, y)', but continue parsing.
4001    if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
4002      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
4003
4004    // Verify that the argument identifier has not already been mentioned.
4005    if (!ParamsSoFar.insert(ParmII)) {
4006      Diag(Tok, diag::err_param_redefinition) << ParmII;
4007    } else {
4008      // Remember this identifier in ParamInfo.
4009      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
4010                                                     Tok.getLocation(),
4011                                                     0));
4012    }
4013
4014    // Eat the identifier.
4015    ConsumeToken();
4016  }
4017
4018  // If we have the closing ')', eat it and we're done.
4019  SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
4020
4021  // Remember that we parsed a function type, and remember the attributes.  This
4022  // function type is always a K&R style function type, which is not varargs and
4023  // has no prototype.
4024  ParsedAttributes attrs(AttrFactory);
4025  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
4026                                             SourceLocation(),
4027                                             &ParamInfo[0], ParamInfo.size(),
4028                                             /*TypeQuals*/0,
4029                                             true, SourceLocation(),
4030                                             EST_None, SourceLocation(), 0, 0,
4031                                             0, 0, LParenLoc, RLoc, D),
4032                attrs, RLoc);
4033}
4034
4035/// [C90]   direct-declarator '[' constant-expression[opt] ']'
4036/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
4037/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
4038/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
4039/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
4040void Parser::ParseBracketDeclarator(Declarator &D) {
4041  SourceLocation StartLoc = ConsumeBracket();
4042
4043  // C array syntax has many features, but by-far the most common is [] and [4].
4044  // This code does a fast path to handle some of the most obvious cases.
4045  if (Tok.getKind() == tok::r_square) {
4046    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4047    ParsedAttributes attrs(AttrFactory);
4048    MaybeParseCXX0XAttributes(attrs);
4049
4050    // Remember that we parsed the empty array type.
4051    ExprResult NumElements;
4052    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
4053                                            StartLoc, EndLoc),
4054                  attrs, EndLoc);
4055    return;
4056  } else if (Tok.getKind() == tok::numeric_constant &&
4057             GetLookAheadToken(1).is(tok::r_square)) {
4058    // [4] is very common.  Parse the numeric constant expression.
4059    ExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
4060    ConsumeToken();
4061
4062    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4063    ParsedAttributes attrs(AttrFactory);
4064    MaybeParseCXX0XAttributes(attrs);
4065
4066    // Remember that we parsed a array type, and remember its features.
4067    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
4068                                            ExprRes.release(),
4069                                            StartLoc, EndLoc),
4070                  attrs, EndLoc);
4071    return;
4072  }
4073
4074  // If valid, this location is the position where we read the 'static' keyword.
4075  SourceLocation StaticLoc;
4076  if (Tok.is(tok::kw_static))
4077    StaticLoc = ConsumeToken();
4078
4079  // If there is a type-qualifier-list, read it now.
4080  // Type qualifiers in an array subscript are a C99 feature.
4081  DeclSpec DS(AttrFactory);
4082  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
4083
4084  // If we haven't already read 'static', check to see if there is one after the
4085  // type-qualifier-list.
4086  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
4087    StaticLoc = ConsumeToken();
4088
4089  // Handle "direct-declarator [ type-qual-list[opt] * ]".
4090  bool isStar = false;
4091  ExprResult NumElements;
4092
4093  // Handle the case where we have '[*]' as the array size.  However, a leading
4094  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
4095  // the the token after the star is a ']'.  Since stars in arrays are
4096  // infrequent, use of lookahead is not costly here.
4097  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
4098    ConsumeToken();  // Eat the '*'.
4099
4100    if (StaticLoc.isValid()) {
4101      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
4102      StaticLoc = SourceLocation();  // Drop the static.
4103    }
4104    isStar = true;
4105  } else if (Tok.isNot(tok::r_square)) {
4106    // Note, in C89, this production uses the constant-expr production instead
4107    // of assignment-expr.  The only difference is that assignment-expr allows
4108    // things like '=' and '*='.  Sema rejects these in C89 mode because they
4109    // are not i-c-e's, so we don't need to distinguish between the two here.
4110
4111    // Parse the constant-expression or assignment-expression now (depending
4112    // on dialect).
4113    if (getLang().CPlusPlus)
4114      NumElements = ParseConstantExpression();
4115    else
4116      NumElements = ParseAssignmentExpression();
4117  }
4118
4119  // If there was an error parsing the assignment-expression, recover.
4120  if (NumElements.isInvalid()) {
4121    D.setInvalidType(true);
4122    // If the expression was invalid, skip it.
4123    SkipUntil(tok::r_square);
4124    return;
4125  }
4126
4127  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4128
4129  ParsedAttributes attrs(AttrFactory);
4130  MaybeParseCXX0XAttributes(attrs);
4131
4132  // Remember that we parsed a array type, and remember its features.
4133  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
4134                                          StaticLoc.isValid(), isStar,
4135                                          NumElements.release(),
4136                                          StartLoc, EndLoc),
4137                attrs, EndLoc);
4138}
4139
4140/// [GNU]   typeof-specifier:
4141///           typeof ( expressions )
4142///           typeof ( type-name )
4143/// [GNU/C++] typeof unary-expression
4144///
4145void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
4146  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
4147  Token OpTok = Tok;
4148  SourceLocation StartLoc = ConsumeToken();
4149
4150  const bool hasParens = Tok.is(tok::l_paren);
4151
4152  bool isCastExpr;
4153  ParsedType CastTy;
4154  SourceRange CastRange;
4155  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
4156                                                          CastTy, CastRange);
4157  if (hasParens)
4158    DS.setTypeofParensRange(CastRange);
4159
4160  if (CastRange.getEnd().isInvalid())
4161    // FIXME: Not accurate, the range gets one token more than it should.
4162    DS.SetRangeEnd(Tok.getLocation());
4163  else
4164    DS.SetRangeEnd(CastRange.getEnd());
4165
4166  if (isCastExpr) {
4167    if (!CastTy) {
4168      DS.SetTypeSpecError();
4169      return;
4170    }
4171
4172    const char *PrevSpec = 0;
4173    unsigned DiagID;
4174    // Check for duplicate type specifiers (e.g. "int typeof(int)").
4175    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
4176                           DiagID, CastTy))
4177      Diag(StartLoc, DiagID) << PrevSpec;
4178    return;
4179  }
4180
4181  // If we get here, the operand to the typeof was an expresion.
4182  if (Operand.isInvalid()) {
4183    DS.SetTypeSpecError();
4184    return;
4185  }
4186
4187  const char *PrevSpec = 0;
4188  unsigned DiagID;
4189  // Check for duplicate type specifiers (e.g. "int typeof(int)").
4190  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
4191                         DiagID, Operand.get()))
4192    Diag(StartLoc, DiagID) << PrevSpec;
4193}
4194
4195
4196/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
4197/// from TryAltiVecVectorToken.
4198bool Parser::TryAltiVecVectorTokenOutOfLine() {
4199  Token Next = NextToken();
4200  switch (Next.getKind()) {
4201  default: return false;
4202  case tok::kw_short:
4203  case tok::kw_long:
4204  case tok::kw_signed:
4205  case tok::kw_unsigned:
4206  case tok::kw_void:
4207  case tok::kw_char:
4208  case tok::kw_int:
4209  case tok::kw_float:
4210  case tok::kw_double:
4211  case tok::kw_bool:
4212  case tok::kw___pixel:
4213    Tok.setKind(tok::kw___vector);
4214    return true;
4215  case tok::identifier:
4216    if (Next.getIdentifierInfo() == Ident_pixel) {
4217      Tok.setKind(tok::kw___vector);
4218      return true;
4219    }
4220    return false;
4221  }
4222}
4223
4224bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
4225                                      const char *&PrevSpec, unsigned &DiagID,
4226                                      bool &isInvalid) {
4227  if (Tok.getIdentifierInfo() == Ident_vector) {
4228    Token Next = NextToken();
4229    switch (Next.getKind()) {
4230    case tok::kw_short:
4231    case tok::kw_long:
4232    case tok::kw_signed:
4233    case tok::kw_unsigned:
4234    case tok::kw_void:
4235    case tok::kw_char:
4236    case tok::kw_int:
4237    case tok::kw_float:
4238    case tok::kw_double:
4239    case tok::kw_bool:
4240    case tok::kw___pixel:
4241      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4242      return true;
4243    case tok::identifier:
4244      if (Next.getIdentifierInfo() == Ident_pixel) {
4245        isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4246        return true;
4247      }
4248      break;
4249    default:
4250      break;
4251    }
4252  } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
4253             DS.isTypeAltiVecVector()) {
4254    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
4255    return true;
4256  }
4257  return false;
4258}
4259