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