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