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