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