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