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