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