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