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