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