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