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