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