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