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