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