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