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