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