ParseDecl.cpp revision c6eb44b321c543c5bcf28727228a0cceced57e2e
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;
1147    tok::TokenKind TagKind = tok::unknown;
1148
1149    switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
1150      default: break;
1151      case DeclSpec::TST_enum:  TagName="enum"  ;TagKind=tok::kw_enum  ;break;
1152      case DeclSpec::TST_union: TagName="union" ;TagKind=tok::kw_union ;break;
1153      case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break;
1154      case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break;
1155    }
1156
1157    if (TagName) {
1158      Diag(Loc, diag::err_use_of_tag_name_without_tag)
1159        << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus
1160        << FixItHint::CreateInsertion(Tok.getLocation(),TagName);
1161
1162      // Parse this as a tag as if the missing tag were present.
1163      if (TagKind == tok::kw_enum)
1164        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1165      else
1166        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
1167      return true;
1168    }
1169  }
1170
1171  // This is almost certainly an invalid type name. Let the action emit a
1172  // diagnostic and attempt to recover.
1173  ParsedType T;
1174  if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
1175                                      getCurScope(), SS, T)) {
1176    // The action emitted a diagnostic, so we don't have to.
1177    if (T) {
1178      // The action has suggested that the type T could be used. Set that as
1179      // the type in the declaration specifiers, consume the would-be type
1180      // name token, and we're done.
1181      const char *PrevSpec;
1182      unsigned DiagID;
1183      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
1184      DS.SetRangeEnd(Tok.getLocation());
1185      ConsumeToken();
1186
1187      // There may be other declaration specifiers after this.
1188      return true;
1189    }
1190
1191    // Fall through; the action had no suggestion for us.
1192  } else {
1193    // The action did not emit a diagnostic, so emit one now.
1194    SourceRange R;
1195    if (SS) R = SS->getRange();
1196    Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
1197  }
1198
1199  // Mark this as an error.
1200  const char *PrevSpec;
1201  unsigned DiagID;
1202  DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
1203  DS.SetRangeEnd(Tok.getLocation());
1204  ConsumeToken();
1205
1206  // TODO: Could inject an invalid typedef decl in an enclosing scope to
1207  // avoid rippling error messages on subsequent uses of the same type,
1208  // could be useful if #include was forgotten.
1209  return false;
1210}
1211
1212/// \brief Determine the declaration specifier context from the declarator
1213/// context.
1214///
1215/// \param Context the declarator context, which is one of the
1216/// Declarator::TheContext enumerator values.
1217Parser::DeclSpecContext
1218Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
1219  if (Context == Declarator::MemberContext)
1220    return DSC_class;
1221  if (Context == Declarator::FileContext)
1222    return DSC_top_level;
1223  return DSC_normal;
1224}
1225
1226/// ParseDeclarationSpecifiers
1227///       declaration-specifiers: [C99 6.7]
1228///         storage-class-specifier declaration-specifiers[opt]
1229///         type-specifier declaration-specifiers[opt]
1230/// [C99]   function-specifier declaration-specifiers[opt]
1231/// [GNU]   attributes declaration-specifiers[opt]
1232///
1233///       storage-class-specifier: [C99 6.7.1]
1234///         'typedef'
1235///         'extern'
1236///         'static'
1237///         'auto'
1238///         'register'
1239/// [C++]   'mutable'
1240/// [GNU]   '__thread'
1241///       function-specifier: [C99 6.7.4]
1242/// [C99]   'inline'
1243/// [C++]   'virtual'
1244/// [C++]   'explicit'
1245/// [OpenCL] '__kernel'
1246///       'friend': [C++ dcl.friend]
1247///       'constexpr': [C++0x dcl.constexpr]
1248
1249///
1250void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
1251                                        const ParsedTemplateInfo &TemplateInfo,
1252                                        AccessSpecifier AS,
1253                                        DeclSpecContext DSContext) {
1254  DS.SetRangeStart(Tok.getLocation());
1255  DS.SetRangeEnd(Tok.getLocation());
1256  while (1) {
1257    bool isInvalid = false;
1258    const char *PrevSpec = 0;
1259    unsigned DiagID = 0;
1260
1261    SourceLocation Loc = Tok.getLocation();
1262
1263    switch (Tok.getKind()) {
1264    default:
1265    DoneWithDeclSpec:
1266      // If this is not a declaration specifier token, we're done reading decl
1267      // specifiers.  First verify that DeclSpec's are consistent.
1268      DS.Finish(Diags, PP);
1269      return;
1270
1271    case tok::code_completion: {
1272      Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
1273      if (DS.hasTypeSpecifier()) {
1274        bool AllowNonIdentifiers
1275          = (getCurScope()->getFlags() & (Scope::ControlScope |
1276                                          Scope::BlockScope |
1277                                          Scope::TemplateParamScope |
1278                                          Scope::FunctionPrototypeScope |
1279                                          Scope::AtCatchScope)) == 0;
1280        bool AllowNestedNameSpecifiers
1281          = DSContext == DSC_top_level ||
1282            (DSContext == DSC_class && DS.isFriendSpecified());
1283
1284        Actions.CodeCompleteDeclSpec(getCurScope(), DS,
1285                                     AllowNonIdentifiers,
1286                                     AllowNestedNameSpecifiers);
1287        ConsumeCodeCompletionToken();
1288        return;
1289      }
1290
1291      if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
1292        CCC = Sema::PCC_LocalDeclarationSpecifiers;
1293      else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
1294        CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
1295                                    : Sema::PCC_Template;
1296      else if (DSContext == DSC_class)
1297        CCC = Sema::PCC_Class;
1298      else if (ObjCImpDecl)
1299        CCC = Sema::PCC_ObjCImplementation;
1300
1301      Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
1302      ConsumeCodeCompletionToken();
1303      return;
1304    }
1305
1306    case tok::coloncolon: // ::foo::bar
1307      // C++ scope specifier.  Annotate and loop, or bail out on error.
1308      if (TryAnnotateCXXScopeToken(true)) {
1309        if (!DS.hasTypeSpecifier())
1310          DS.SetTypeSpecError();
1311        goto DoneWithDeclSpec;
1312      }
1313      if (Tok.is(tok::coloncolon)) // ::new or ::delete
1314        goto DoneWithDeclSpec;
1315      continue;
1316
1317    case tok::annot_cxxscope: {
1318      if (DS.hasTypeSpecifier())
1319        goto DoneWithDeclSpec;
1320
1321      CXXScopeSpec SS;
1322      Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1323                                                   Tok.getAnnotationRange(),
1324                                                   SS);
1325
1326      // We are looking for a qualified typename.
1327      Token Next = NextToken();
1328      if (Next.is(tok::annot_template_id) &&
1329          static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
1330            ->Kind == TNK_Type_template) {
1331        // We have a qualified template-id, e.g., N::A<int>
1332
1333        // C++ [class.qual]p2:
1334        //   In a lookup in which the constructor is an acceptable lookup
1335        //   result and the nested-name-specifier nominates a class C:
1336        //
1337        //     - if the name specified after the
1338        //       nested-name-specifier, when looked up in C, is the
1339        //       injected-class-name of C (Clause 9), or
1340        //
1341        //     - if the name specified after the nested-name-specifier
1342        //       is the same as the identifier or the
1343        //       simple-template-id's template-name in the last
1344        //       component of the nested-name-specifier,
1345        //
1346        //   the name is instead considered to name the constructor of
1347        //   class C.
1348        //
1349        // Thus, if the template-name is actually the constructor
1350        // name, then the code is ill-formed; this interpretation is
1351        // reinforced by the NAD status of core issue 635.
1352        TemplateIdAnnotation *TemplateId
1353          = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue());
1354        if ((DSContext == DSC_top_level ||
1355             (DSContext == DSC_class && DS.isFriendSpecified())) &&
1356            TemplateId->Name &&
1357            Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
1358          if (isConstructorDeclarator()) {
1359            // The user meant this to be an out-of-line constructor
1360            // definition, but template arguments are not allowed
1361            // there.  Just allow this as a constructor; we'll
1362            // complain about it later.
1363            goto DoneWithDeclSpec;
1364          }
1365
1366          // The user meant this to name a type, but it actually names
1367          // a constructor with some extraneous template
1368          // arguments. Complain, then parse it as a type as the user
1369          // intended.
1370          Diag(TemplateId->TemplateNameLoc,
1371               diag::err_out_of_line_template_id_names_constructor)
1372            << TemplateId->Name;
1373        }
1374
1375        DS.getTypeSpecScope() = SS;
1376        ConsumeToken(); // The C++ scope.
1377        assert(Tok.is(tok::annot_template_id) &&
1378               "ParseOptionalCXXScopeSpecifier not working");
1379        AnnotateTemplateIdTokenAsType();
1380        continue;
1381      }
1382
1383      if (Next.is(tok::annot_typename)) {
1384        DS.getTypeSpecScope() = SS;
1385        ConsumeToken(); // The C++ scope.
1386        if (Tok.getAnnotationValue()) {
1387          ParsedType T = getTypeAnnotation(Tok);
1388          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1389                                         Tok.getAnnotationEndLoc(),
1390                                         PrevSpec, DiagID, T);
1391        }
1392        else
1393          DS.SetTypeSpecError();
1394        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1395        ConsumeToken(); // The typename
1396      }
1397
1398      if (Next.isNot(tok::identifier))
1399        goto DoneWithDeclSpec;
1400
1401      // If we're in a context where the identifier could be a class name,
1402      // check whether this is a constructor declaration.
1403      if ((DSContext == DSC_top_level ||
1404           (DSContext == DSC_class && DS.isFriendSpecified())) &&
1405          Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
1406                                     &SS)) {
1407        if (isConstructorDeclarator())
1408          goto DoneWithDeclSpec;
1409
1410        // As noted in C++ [class.qual]p2 (cited above), when the name
1411        // of the class is qualified in a context where it could name
1412        // a constructor, its a constructor name. However, we've
1413        // looked at the declarator, and the user probably meant this
1414        // to be a type. Complain that it isn't supposed to be treated
1415        // as a type, then proceed to parse it as a type.
1416        Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
1417          << Next.getIdentifierInfo();
1418      }
1419
1420      ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
1421                                               Next.getLocation(),
1422                                               getCurScope(), &SS,
1423                                               false, false, ParsedType(),
1424                                               /*NonTrivialSourceInfo=*/true);
1425
1426      // If the referenced identifier is not a type, then this declspec is
1427      // erroneous: We already checked about that it has no type specifier, and
1428      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
1429      // typename.
1430      if (TypeRep == 0) {
1431        ConsumeToken();   // Eat the scope spec so the identifier is current.
1432        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
1433        goto DoneWithDeclSpec;
1434      }
1435
1436      DS.getTypeSpecScope() = SS;
1437      ConsumeToken(); // The C++ scope.
1438
1439      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1440                                     DiagID, TypeRep);
1441      if (isInvalid)
1442        break;
1443
1444      DS.SetRangeEnd(Tok.getLocation());
1445      ConsumeToken(); // The typename.
1446
1447      continue;
1448    }
1449
1450    case tok::annot_typename: {
1451      if (Tok.getAnnotationValue()) {
1452        ParsedType T = getTypeAnnotation(Tok);
1453        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1454                                       DiagID, T);
1455      } else
1456        DS.SetTypeSpecError();
1457
1458      if (isInvalid)
1459        break;
1460
1461      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1462      ConsumeToken(); // The typename
1463
1464      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1465      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1466      // Objective-C interface.
1467      if (Tok.is(tok::less) && getLang().ObjC1)
1468        ParseObjCProtocolQualifiers(DS);
1469
1470      continue;
1471    }
1472
1473      // typedef-name
1474    case tok::identifier: {
1475      // In C++, check to see if this is a scope specifier like foo::bar::, if
1476      // so handle it as such.  This is important for ctor parsing.
1477      if (getLang().CPlusPlus) {
1478        if (TryAnnotateCXXScopeToken(true)) {
1479          if (!DS.hasTypeSpecifier())
1480            DS.SetTypeSpecError();
1481          goto DoneWithDeclSpec;
1482        }
1483        if (!Tok.is(tok::identifier))
1484          continue;
1485      }
1486
1487      // This identifier can only be a typedef name if we haven't already seen
1488      // a type-specifier.  Without this check we misparse:
1489      //  typedef int X; struct Y { short X; };  as 'short int'.
1490      if (DS.hasTypeSpecifier())
1491        goto DoneWithDeclSpec;
1492
1493      // Check for need to substitute AltiVec keyword tokens.
1494      if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1495        break;
1496
1497      // It has to be available as a typedef too!
1498      ParsedType TypeRep =
1499        Actions.getTypeName(*Tok.getIdentifierInfo(),
1500                            Tok.getLocation(), getCurScope());
1501
1502      // If this is not a typedef name, don't parse it as part of the declspec,
1503      // it must be an implicit int or an error.
1504      if (!TypeRep) {
1505        if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
1506        goto DoneWithDeclSpec;
1507      }
1508
1509      // If we're in a context where the identifier could be a class name,
1510      // check whether this is a constructor declaration.
1511      if (getLang().CPlusPlus && DSContext == DSC_class &&
1512          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
1513          isConstructorDeclarator())
1514        goto DoneWithDeclSpec;
1515
1516      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1517                                     DiagID, TypeRep);
1518      if (isInvalid)
1519        break;
1520
1521      DS.SetRangeEnd(Tok.getLocation());
1522      ConsumeToken(); // The identifier
1523
1524      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1525      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1526      // Objective-C interface.
1527      if (Tok.is(tok::less) && getLang().ObjC1)
1528        ParseObjCProtocolQualifiers(DS);
1529
1530      // Need to support trailing type qualifiers (e.g. "id<p> const").
1531      // If a type specifier follows, it will be diagnosed elsewhere.
1532      continue;
1533    }
1534
1535      // type-name
1536    case tok::annot_template_id: {
1537      TemplateIdAnnotation *TemplateId
1538        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1539      if (TemplateId->Kind != TNK_Type_template) {
1540        // This template-id does not refer to a type name, so we're
1541        // done with the type-specifiers.
1542        goto DoneWithDeclSpec;
1543      }
1544
1545      // If we're in a context where the template-id could be a
1546      // constructor name or specialization, check whether this is a
1547      // constructor declaration.
1548      if (getLang().CPlusPlus && DSContext == DSC_class &&
1549          Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
1550          isConstructorDeclarator())
1551        goto DoneWithDeclSpec;
1552
1553      // Turn the template-id annotation token into a type annotation
1554      // token, then try again to parse it as a type-specifier.
1555      AnnotateTemplateIdTokenAsType();
1556      continue;
1557    }
1558
1559    // GNU attributes support.
1560    case tok::kw___attribute:
1561      ParseGNUAttributes(DS.getAttributes());
1562      continue;
1563
1564    // Microsoft declspec support.
1565    case tok::kw___declspec:
1566      ParseMicrosoftDeclSpec(DS.getAttributes());
1567      continue;
1568
1569    // Microsoft single token adornments.
1570    case tok::kw___forceinline:
1571      // FIXME: Add handling here!
1572      break;
1573
1574    case tok::kw___ptr64:
1575    case tok::kw___w64:
1576    case tok::kw___cdecl:
1577    case tok::kw___stdcall:
1578    case tok::kw___fastcall:
1579    case tok::kw___thiscall:
1580      ParseMicrosoftTypeAttributes(DS.getAttributes());
1581      continue;
1582
1583    // Borland single token adornments.
1584    case tok::kw___pascal:
1585      ParseBorlandTypeAttributes(DS.getAttributes());
1586      continue;
1587
1588    // OpenCL single token adornments.
1589    case tok::kw___kernel:
1590      ParseOpenCLAttributes(DS.getAttributes());
1591      continue;
1592
1593    // storage-class-specifier
1594    case tok::kw_typedef:
1595      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
1596                                         DiagID, getLang());
1597      break;
1598    case tok::kw_extern:
1599      if (DS.isThreadSpecified())
1600        Diag(Tok, diag::ext_thread_before) << "extern";
1601      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1602                                         DiagID, getLang());
1603      break;
1604    case tok::kw___private_extern__:
1605      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1606                                         PrevSpec, DiagID, getLang());
1607      break;
1608    case tok::kw_static:
1609      if (DS.isThreadSpecified())
1610        Diag(Tok, diag::ext_thread_before) << "static";
1611      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1612                                         DiagID, getLang());
1613      break;
1614    case tok::kw_auto:
1615      if (getLang().CPlusPlus0x) {
1616        if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
1617          isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1618                                           DiagID, getLang());
1619          if (!isInvalid)
1620            Diag(Tok, diag::auto_storage_class)
1621              << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
1622        }
1623        else
1624          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1625                                         DiagID);
1626      }
1627      else
1628        isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1629                                           DiagID, getLang());
1630      break;
1631    case tok::kw_register:
1632      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1633                                         DiagID, getLang());
1634      break;
1635    case tok::kw_mutable:
1636      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1637                                         DiagID, getLang());
1638      break;
1639    case tok::kw___thread:
1640      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1641      break;
1642
1643    // function-specifier
1644    case tok::kw_inline:
1645      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1646      break;
1647    case tok::kw_virtual:
1648      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1649      break;
1650    case tok::kw_explicit:
1651      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1652      break;
1653
1654    // friend
1655    case tok::kw_friend:
1656      if (DSContext == DSC_class)
1657        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1658      else {
1659        PrevSpec = ""; // not actually used by the diagnostic
1660        DiagID = diag::err_friend_invalid_in_context;
1661        isInvalid = true;
1662      }
1663      break;
1664
1665    // constexpr
1666    case tok::kw_constexpr:
1667      isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
1668      break;
1669
1670    // type-specifier
1671    case tok::kw_short:
1672      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1673                                      DiagID);
1674      break;
1675    case tok::kw_long:
1676      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1677        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1678                                        DiagID);
1679      else
1680        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1681                                        DiagID);
1682      break;
1683    case tok::kw_signed:
1684      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1685                                     DiagID);
1686      break;
1687    case tok::kw_unsigned:
1688      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1689                                     DiagID);
1690      break;
1691    case tok::kw__Complex:
1692      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1693                                        DiagID);
1694      break;
1695    case tok::kw__Imaginary:
1696      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1697                                        DiagID);
1698      break;
1699    case tok::kw_void:
1700      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1701                                     DiagID);
1702      break;
1703    case tok::kw_char:
1704      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1705                                     DiagID);
1706      break;
1707    case tok::kw_int:
1708      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1709                                     DiagID);
1710      break;
1711    case tok::kw_float:
1712      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1713                                     DiagID);
1714      break;
1715    case tok::kw_double:
1716      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1717                                     DiagID);
1718      break;
1719    case tok::kw_wchar_t:
1720      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1721                                     DiagID);
1722      break;
1723    case tok::kw_char16_t:
1724      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1725                                     DiagID);
1726      break;
1727    case tok::kw_char32_t:
1728      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1729                                     DiagID);
1730      break;
1731    case tok::kw_bool:
1732    case tok::kw__Bool:
1733      if (Tok.is(tok::kw_bool) &&
1734          DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
1735          DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1736        PrevSpec = ""; // Not used by the diagnostic.
1737        DiagID = diag::err_bool_redeclaration;
1738        isInvalid = true;
1739      } else {
1740        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1741                                       DiagID);
1742      }
1743      break;
1744    case tok::kw__Decimal32:
1745      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1746                                     DiagID);
1747      break;
1748    case tok::kw__Decimal64:
1749      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1750                                     DiagID);
1751      break;
1752    case tok::kw__Decimal128:
1753      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1754                                     DiagID);
1755      break;
1756    case tok::kw___vector:
1757      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1758      break;
1759    case tok::kw___pixel:
1760      isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1761      break;
1762    case tok::kw___unknown_anytype:
1763      isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
1764                                     PrevSpec, DiagID);
1765      break;
1766
1767    // class-specifier:
1768    case tok::kw_class:
1769    case tok::kw_struct:
1770    case tok::kw_union: {
1771      tok::TokenKind Kind = Tok.getKind();
1772      ConsumeToken();
1773      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1774      continue;
1775    }
1776
1777    // enum-specifier:
1778    case tok::kw_enum:
1779      ConsumeToken();
1780      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1781      continue;
1782
1783    // cv-qualifier:
1784    case tok::kw_const:
1785      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1786                                 getLang());
1787      break;
1788    case tok::kw_volatile:
1789      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1790                                 getLang());
1791      break;
1792    case tok::kw_restrict:
1793      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1794                                 getLang());
1795      break;
1796
1797    // C++ typename-specifier:
1798    case tok::kw_typename:
1799      if (TryAnnotateTypeOrScopeToken()) {
1800        DS.SetTypeSpecError();
1801        goto DoneWithDeclSpec;
1802      }
1803      if (!Tok.is(tok::kw_typename))
1804        continue;
1805      break;
1806
1807    // GNU typeof support.
1808    case tok::kw_typeof:
1809      ParseTypeofSpecifier(DS);
1810      continue;
1811
1812    case tok::kw_decltype:
1813      ParseDecltypeSpecifier(DS);
1814      continue;
1815
1816    // OpenCL qualifiers:
1817    case tok::kw_private:
1818      if (!getLang().OpenCL)
1819        goto DoneWithDeclSpec;
1820    case tok::kw___private:
1821    case tok::kw___global:
1822    case tok::kw___local:
1823    case tok::kw___constant:
1824    case tok::kw___read_only:
1825    case tok::kw___write_only:
1826    case tok::kw___read_write:
1827      ParseOpenCLQualifiers(DS);
1828      break;
1829
1830    case tok::less:
1831      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1832      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
1833      // but we support it.
1834      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1835        goto DoneWithDeclSpec;
1836
1837      if (!ParseObjCProtocolQualifiers(DS))
1838        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1839          << FixItHint::CreateInsertion(Loc, "id")
1840          << SourceRange(Loc, DS.getSourceRange().getEnd());
1841
1842      // Need to support trailing type qualifiers (e.g. "id<p> const").
1843      // If a type specifier follows, it will be diagnosed elsewhere.
1844      continue;
1845    }
1846    // If the specifier wasn't legal, issue a diagnostic.
1847    if (isInvalid) {
1848      assert(PrevSpec && "Method did not return previous specifier!");
1849      assert(DiagID);
1850
1851      if (DiagID == diag::ext_duplicate_declspec)
1852        Diag(Tok, DiagID)
1853          << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
1854      else
1855        Diag(Tok, DiagID) << PrevSpec;
1856    }
1857
1858    DS.SetRangeEnd(Tok.getLocation());
1859    ConsumeToken();
1860  }
1861}
1862
1863/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1864/// primarily follow the C++ grammar with additions for C99 and GNU,
1865/// which together subsume the C grammar. Note that the C++
1866/// type-specifier also includes the C type-qualifier (for const,
1867/// volatile, and C99 restrict). Returns true if a type-specifier was
1868/// found (and parsed), false otherwise.
1869///
1870///       type-specifier: [C++ 7.1.5]
1871///         simple-type-specifier
1872///         class-specifier
1873///         enum-specifier
1874///         elaborated-type-specifier  [TODO]
1875///         cv-qualifier
1876///
1877///       cv-qualifier: [C++ 7.1.5.1]
1878///         'const'
1879///         'volatile'
1880/// [C99]   'restrict'
1881///
1882///       simple-type-specifier: [ C++ 7.1.5.2]
1883///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
1884///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
1885///         'char'
1886///         'wchar_t'
1887///         'bool'
1888///         'short'
1889///         'int'
1890///         'long'
1891///         'signed'
1892///         'unsigned'
1893///         'float'
1894///         'double'
1895///         'void'
1896/// [C99]   '_Bool'
1897/// [C99]   '_Complex'
1898/// [C99]   '_Imaginary'  // Removed in TC2?
1899/// [GNU]   '_Decimal32'
1900/// [GNU]   '_Decimal64'
1901/// [GNU]   '_Decimal128'
1902/// [GNU]   typeof-specifier
1903/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
1904/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
1905/// [C++0x] 'decltype' ( expression )
1906/// [AltiVec] '__vector'
1907bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1908                                        const char *&PrevSpec,
1909                                        unsigned &DiagID,
1910                                        const ParsedTemplateInfo &TemplateInfo,
1911                                        bool SuppressDeclarations) {
1912  SourceLocation Loc = Tok.getLocation();
1913
1914  switch (Tok.getKind()) {
1915  case tok::identifier:   // foo::bar
1916    // If we already have a type specifier, this identifier is not a type.
1917    if (DS.getTypeSpecType() != DeclSpec::TST_unspecified ||
1918        DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
1919        DS.getTypeSpecSign() != DeclSpec::TSS_unspecified)
1920      return false;
1921    // Check for need to substitute AltiVec keyword tokens.
1922    if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1923      break;
1924    // Fall through.
1925  case tok::kw_typename:  // typename foo::bar
1926    // Annotate typenames and C++ scope specifiers.  If we get one, just
1927    // recurse to handle whatever we get.
1928    if (TryAnnotateTypeOrScopeToken())
1929      return true;
1930    if (Tok.is(tok::identifier))
1931      return false;
1932    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1933                                      TemplateInfo, SuppressDeclarations);
1934  case tok::coloncolon:   // ::foo::bar
1935    if (NextToken().is(tok::kw_new) ||    // ::new
1936        NextToken().is(tok::kw_delete))   // ::delete
1937      return false;
1938
1939    // Annotate typenames and C++ scope specifiers.  If we get one, just
1940    // recurse to handle whatever we get.
1941    if (TryAnnotateTypeOrScopeToken())
1942      return true;
1943    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1944                                      TemplateInfo, SuppressDeclarations);
1945
1946  // simple-type-specifier:
1947  case tok::annot_typename: {
1948    if (ParsedType T = getTypeAnnotation(Tok)) {
1949      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1950                                     Tok.getAnnotationEndLoc(), PrevSpec,
1951                                     DiagID, T);
1952    } else
1953      DS.SetTypeSpecError();
1954    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1955    ConsumeToken(); // The typename
1956
1957    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1958    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1959    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1960    // just a normal reference to a typedef name.
1961    if (Tok.is(tok::less) && getLang().ObjC1)
1962      ParseObjCProtocolQualifiers(DS);
1963
1964    return true;
1965  }
1966
1967  case tok::kw_short:
1968    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1969    break;
1970  case tok::kw_long:
1971    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1972      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1973                                      DiagID);
1974    else
1975      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1976                                      DiagID);
1977    break;
1978  case tok::kw_signed:
1979    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1980    break;
1981  case tok::kw_unsigned:
1982    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1983                                   DiagID);
1984    break;
1985  case tok::kw__Complex:
1986    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1987                                      DiagID);
1988    break;
1989  case tok::kw__Imaginary:
1990    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1991                                      DiagID);
1992    break;
1993  case tok::kw_void:
1994    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1995    break;
1996  case tok::kw_char:
1997    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1998    break;
1999  case tok::kw_int:
2000    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
2001    break;
2002  case tok::kw_float:
2003    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
2004    break;
2005  case tok::kw_double:
2006    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
2007    break;
2008  case tok::kw_wchar_t:
2009    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
2010    break;
2011  case tok::kw_char16_t:
2012    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
2013    break;
2014  case tok::kw_char32_t:
2015    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
2016    break;
2017  case tok::kw_bool:
2018  case tok::kw__Bool:
2019    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
2020    break;
2021  case tok::kw__Decimal32:
2022    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
2023                                   DiagID);
2024    break;
2025  case tok::kw__Decimal64:
2026    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
2027                                   DiagID);
2028    break;
2029  case tok::kw__Decimal128:
2030    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
2031                                   DiagID);
2032    break;
2033  case tok::kw___vector:
2034    isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
2035    break;
2036  case tok::kw___pixel:
2037    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
2038    break;
2039
2040  // class-specifier:
2041  case tok::kw_class:
2042  case tok::kw_struct:
2043  case tok::kw_union: {
2044    tok::TokenKind Kind = Tok.getKind();
2045    ConsumeToken();
2046    ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none,
2047                        SuppressDeclarations);
2048    return true;
2049  }
2050
2051  // enum-specifier:
2052  case tok::kw_enum:
2053    ConsumeToken();
2054    ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none);
2055    return true;
2056
2057  // cv-qualifier:
2058  case tok::kw_const:
2059    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
2060                               DiagID, getLang());
2061    break;
2062  case tok::kw_volatile:
2063    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
2064                               DiagID, getLang());
2065    break;
2066  case tok::kw_restrict:
2067    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
2068                               DiagID, getLang());
2069    break;
2070
2071  // GNU typeof support.
2072  case tok::kw_typeof:
2073    ParseTypeofSpecifier(DS);
2074    return true;
2075
2076  // C++0x decltype support.
2077  case tok::kw_decltype:
2078    ParseDecltypeSpecifier(DS);
2079    return true;
2080
2081  // OpenCL qualifiers:
2082  case tok::kw_private:
2083    if (!getLang().OpenCL)
2084      return false;
2085  case tok::kw___private:
2086  case tok::kw___global:
2087  case tok::kw___local:
2088  case tok::kw___constant:
2089  case tok::kw___read_only:
2090  case tok::kw___write_only:
2091  case tok::kw___read_write:
2092    ParseOpenCLQualifiers(DS);
2093    break;
2094
2095  // C++0x auto support.
2096  case tok::kw_auto:
2097    if (!getLang().CPlusPlus0x)
2098      return false;
2099
2100    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
2101    break;
2102
2103  case tok::kw___ptr64:
2104  case tok::kw___w64:
2105  case tok::kw___cdecl:
2106  case tok::kw___stdcall:
2107  case tok::kw___fastcall:
2108  case tok::kw___thiscall:
2109    ParseMicrosoftTypeAttributes(DS.getAttributes());
2110    return true;
2111
2112  case tok::kw___pascal:
2113    ParseBorlandTypeAttributes(DS.getAttributes());
2114    return true;
2115
2116  default:
2117    // Not a type-specifier; do nothing.
2118    return false;
2119  }
2120
2121  // If the specifier combination wasn't legal, issue a diagnostic.
2122  if (isInvalid) {
2123    assert(PrevSpec && "Method did not return previous specifier!");
2124    // Pick between error or extwarn.
2125    Diag(Tok, DiagID) << PrevSpec;
2126  }
2127  DS.SetRangeEnd(Tok.getLocation());
2128  ConsumeToken(); // whatever we parsed above.
2129  return true;
2130}
2131
2132/// ParseStructDeclaration - Parse a struct declaration without the terminating
2133/// semicolon.
2134///
2135///       struct-declaration:
2136///         specifier-qualifier-list struct-declarator-list
2137/// [GNU]   __extension__ struct-declaration
2138/// [GNU]   specifier-qualifier-list
2139///       struct-declarator-list:
2140///         struct-declarator
2141///         struct-declarator-list ',' struct-declarator
2142/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
2143///       struct-declarator:
2144///         declarator
2145/// [GNU]   declarator attributes[opt]
2146///         declarator[opt] ':' constant-expression
2147/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
2148///
2149void Parser::
2150ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
2151  if (Tok.is(tok::kw___extension__)) {
2152    // __extension__ silences extension warnings in the subexpression.
2153    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
2154    ConsumeToken();
2155    return ParseStructDeclaration(DS, Fields);
2156  }
2157
2158  // Parse the common specifier-qualifiers-list piece.
2159  ParseSpecifierQualifierList(DS);
2160
2161  // If there are no declarators, this is a free-standing declaration
2162  // specifier. Let the actions module cope with it.
2163  if (Tok.is(tok::semi)) {
2164    Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS);
2165    return;
2166  }
2167
2168  // Read struct-declarators until we find the semicolon.
2169  bool FirstDeclarator = true;
2170  while (1) {
2171    ParsingDeclRAIIObject PD(*this);
2172    FieldDeclarator DeclaratorInfo(DS);
2173
2174    // Attributes are only allowed here on successive declarators.
2175    if (!FirstDeclarator)
2176      MaybeParseGNUAttributes(DeclaratorInfo.D);
2177
2178    /// struct-declarator: declarator
2179    /// struct-declarator: declarator[opt] ':' constant-expression
2180    if (Tok.isNot(tok::colon)) {
2181      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2182      ColonProtectionRAIIObject X(*this);
2183      ParseDeclarator(DeclaratorInfo.D);
2184    }
2185
2186    if (Tok.is(tok::colon)) {
2187      ConsumeToken();
2188      ExprResult Res(ParseConstantExpression());
2189      if (Res.isInvalid())
2190        SkipUntil(tok::semi, true, true);
2191      else
2192        DeclaratorInfo.BitfieldSize = Res.release();
2193    }
2194
2195    // If attributes exist after the declarator, parse them.
2196    MaybeParseGNUAttributes(DeclaratorInfo.D);
2197
2198    // We're done with this declarator;  invoke the callback.
2199    Decl *D = Fields.invoke(DeclaratorInfo);
2200    PD.complete(D);
2201
2202    // If we don't have a comma, it is either the end of the list (a ';')
2203    // or an error, bail out.
2204    if (Tok.isNot(tok::comma))
2205      return;
2206
2207    // Consume the comma.
2208    ConsumeToken();
2209
2210    FirstDeclarator = false;
2211  }
2212}
2213
2214/// ParseStructUnionBody
2215///       struct-contents:
2216///         struct-declaration-list
2217/// [EXT]   empty
2218/// [GNU]   "struct-declaration-list" without terminatoring ';'
2219///       struct-declaration-list:
2220///         struct-declaration
2221///         struct-declaration-list struct-declaration
2222/// [OBC]   '@' 'defs' '(' class-name ')'
2223///
2224void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
2225                                  unsigned TagType, Decl *TagDecl) {
2226  PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2227                                      "parsing struct/union body");
2228
2229  SourceLocation LBraceLoc = ConsumeBrace();
2230
2231  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
2232  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2233
2234  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
2235  // C++.
2236  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
2237    Diag(Tok, diag::ext_empty_struct_union)
2238      << (TagType == TST_union);
2239
2240  llvm::SmallVector<Decl *, 32> FieldDecls;
2241
2242  // While we still have something to read, read the declarations in the struct.
2243  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2244    // Each iteration of this loop reads one struct-declaration.
2245
2246    // Check for extraneous top-level semicolon.
2247    if (Tok.is(tok::semi)) {
2248      Diag(Tok, diag::ext_extra_struct_semi)
2249        << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
2250        << FixItHint::CreateRemoval(Tok.getLocation());
2251      ConsumeToken();
2252      continue;
2253    }
2254
2255    // Parse all the comma separated declarators.
2256    DeclSpec DS(AttrFactory);
2257
2258    if (!Tok.is(tok::at)) {
2259      struct CFieldCallback : FieldCallback {
2260        Parser &P;
2261        Decl *TagDecl;
2262        llvm::SmallVectorImpl<Decl *> &FieldDecls;
2263
2264        CFieldCallback(Parser &P, Decl *TagDecl,
2265                       llvm::SmallVectorImpl<Decl *> &FieldDecls) :
2266          P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
2267
2268        virtual Decl *invoke(FieldDeclarator &FD) {
2269          // Install the declarator into the current TagDecl.
2270          Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
2271                              FD.D.getDeclSpec().getSourceRange().getBegin(),
2272                                                 FD.D, FD.BitfieldSize);
2273          FieldDecls.push_back(Field);
2274          return Field;
2275        }
2276      } Callback(*this, TagDecl, FieldDecls);
2277
2278      ParseStructDeclaration(DS, Callback);
2279    } else { // Handle @defs
2280      ConsumeToken();
2281      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
2282        Diag(Tok, diag::err_unexpected_at);
2283        SkipUntil(tok::semi, true);
2284        continue;
2285      }
2286      ConsumeToken();
2287      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
2288      if (!Tok.is(tok::identifier)) {
2289        Diag(Tok, diag::err_expected_ident);
2290        SkipUntil(tok::semi, true);
2291        continue;
2292      }
2293      llvm::SmallVector<Decl *, 16> Fields;
2294      Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
2295                        Tok.getIdentifierInfo(), Fields);
2296      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
2297      ConsumeToken();
2298      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
2299    }
2300
2301    if (Tok.is(tok::semi)) {
2302      ConsumeToken();
2303    } else if (Tok.is(tok::r_brace)) {
2304      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
2305      break;
2306    } else {
2307      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
2308      // Skip to end of block or statement to avoid ext-warning on extra ';'.
2309      SkipUntil(tok::r_brace, true, true);
2310      // If we stopped at a ';', eat it.
2311      if (Tok.is(tok::semi)) ConsumeToken();
2312    }
2313  }
2314
2315  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2316
2317  ParsedAttributes attrs(AttrFactory);
2318  // If attributes exist after struct contents, parse them.
2319  MaybeParseGNUAttributes(attrs);
2320
2321  Actions.ActOnFields(getCurScope(),
2322                      RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
2323                      LBraceLoc, RBraceLoc,
2324                      attrs.getList());
2325  StructScope.Exit();
2326  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc);
2327}
2328
2329/// ParseEnumSpecifier
2330///       enum-specifier: [C99 6.7.2.2]
2331///         'enum' identifier[opt] '{' enumerator-list '}'
2332///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
2333/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
2334///                                                 '}' attributes[opt]
2335///         'enum' identifier
2336/// [GNU]   'enum' attributes[opt] identifier
2337///
2338/// [C++0x] enum-head '{' enumerator-list[opt] '}'
2339/// [C++0x] enum-head '{' enumerator-list ','  '}'
2340///
2341///       enum-head: [C++0x]
2342///         enum-key attributes[opt] identifier[opt] enum-base[opt]
2343///         enum-key attributes[opt] nested-name-specifier identifier enum-base[opt]
2344///
2345///       enum-key: [C++0x]
2346///         'enum'
2347///         'enum' 'class'
2348///         'enum' 'struct'
2349///
2350///       enum-base: [C++0x]
2351///         ':' type-specifier-seq
2352///
2353/// [C++] elaborated-type-specifier:
2354/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
2355///
2356void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
2357                                const ParsedTemplateInfo &TemplateInfo,
2358                                AccessSpecifier AS) {
2359  // Parse the tag portion of this.
2360  if (Tok.is(tok::code_completion)) {
2361    // Code completion for an enum name.
2362    Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
2363    ConsumeCodeCompletionToken();
2364  }
2365
2366  // If attributes exist after tag, parse them.
2367  ParsedAttributes attrs(AttrFactory);
2368  MaybeParseGNUAttributes(attrs);
2369
2370  CXXScopeSpec &SS = DS.getTypeSpecScope();
2371  if (getLang().CPlusPlus) {
2372    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false))
2373      return;
2374
2375    if (SS.isSet() && Tok.isNot(tok::identifier)) {
2376      Diag(Tok, diag::err_expected_ident);
2377      if (Tok.isNot(tok::l_brace)) {
2378        // Has no name and is not a definition.
2379        // Skip the rest of this declarator, up until the comma or semicolon.
2380        SkipUntil(tok::comma, true);
2381        return;
2382      }
2383    }
2384  }
2385
2386  bool AllowFixedUnderlyingType = getLang().CPlusPlus0x || getLang().Microsoft;
2387  bool IsScopedEnum = false;
2388  bool IsScopedUsingClassTag = false;
2389
2390  if (getLang().CPlusPlus0x &&
2391      (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
2392    IsScopedEnum = true;
2393    IsScopedUsingClassTag = Tok.is(tok::kw_class);
2394    ConsumeToken();
2395  }
2396
2397  // Must have either 'enum name' or 'enum {...}'.
2398  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
2399      (AllowFixedUnderlyingType && Tok.isNot(tok::colon))) {
2400    Diag(Tok, diag::err_expected_ident_lbrace);
2401
2402    // Skip the rest of this declarator, up until the comma or semicolon.
2403    SkipUntil(tok::comma, true);
2404    return;
2405  }
2406
2407  // If an identifier is present, consume and remember it.
2408  IdentifierInfo *Name = 0;
2409  SourceLocation NameLoc;
2410  if (Tok.is(tok::identifier)) {
2411    Name = Tok.getIdentifierInfo();
2412    NameLoc = ConsumeToken();
2413  }
2414
2415  if (!Name && IsScopedEnum) {
2416    // C++0x 7.2p2: The optional identifier shall not be omitted in the
2417    // declaration of a scoped enumeration.
2418    Diag(Tok, diag::err_scoped_enum_missing_identifier);
2419    IsScopedEnum = false;
2420    IsScopedUsingClassTag = false;
2421  }
2422
2423  TypeResult BaseType;
2424
2425  // Parse the fixed underlying type.
2426  if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
2427    bool PossibleBitfield = false;
2428    if (getCurScope()->getFlags() & Scope::ClassScope) {
2429      // If we're in class scope, this can either be an enum declaration with
2430      // an underlying type, or a declaration of a bitfield member. We try to
2431      // use a simple disambiguation scheme first to catch the common cases
2432      // (integer literal, sizeof); if it's still ambiguous, we then consider
2433      // anything that's a simple-type-specifier followed by '(' as an
2434      // expression. This suffices because function types are not valid
2435      // underlying types anyway.
2436      TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
2437      // If the next token starts an expression, we know we're parsing a
2438      // bit-field. This is the common case.
2439      if (TPR == TPResult::True())
2440        PossibleBitfield = true;
2441      // If the next token starts a type-specifier-seq, it may be either a
2442      // a fixed underlying type or the start of a function-style cast in C++;
2443      // lookahead one more token to see if it's obvious that we have a
2444      // fixed underlying type.
2445      else if (TPR == TPResult::False() &&
2446               GetLookAheadToken(2).getKind() == tok::semi) {
2447        // Consume the ':'.
2448        ConsumeToken();
2449      } else {
2450        // We have the start of a type-specifier-seq, so we have to perform
2451        // tentative parsing to determine whether we have an expression or a
2452        // type.
2453        TentativeParsingAction TPA(*this);
2454
2455        // Consume the ':'.
2456        ConsumeToken();
2457
2458        if ((getLang().CPlusPlus &&
2459             isCXXDeclarationSpecifier() != TPResult::True()) ||
2460            (!getLang().CPlusPlus && !isDeclarationSpecifier(true))) {
2461          // We'll parse this as a bitfield later.
2462          PossibleBitfield = true;
2463          TPA.Revert();
2464        } else {
2465          // We have a type-specifier-seq.
2466          TPA.Commit();
2467        }
2468      }
2469    } else {
2470      // Consume the ':'.
2471      ConsumeToken();
2472    }
2473
2474    if (!PossibleBitfield) {
2475      SourceRange Range;
2476      BaseType = ParseTypeName(&Range);
2477
2478      if (!getLang().CPlusPlus0x)
2479        Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type)
2480          << Range;
2481    }
2482  }
2483
2484  // There are three options here.  If we have 'enum foo;', then this is a
2485  // forward declaration.  If we have 'enum foo {...' then this is a
2486  // definition. Otherwise we have something like 'enum foo xyz', a reference.
2487  //
2488  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
2489  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
2490  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
2491  //
2492  Sema::TagUseKind TUK;
2493  if (Tok.is(tok::l_brace))
2494    TUK = Sema::TUK_Definition;
2495  else if (Tok.is(tok::semi))
2496    TUK = Sema::TUK_Declaration;
2497  else
2498    TUK = Sema::TUK_Reference;
2499
2500  // enums cannot be templates, although they can be referenced from a
2501  // template.
2502  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
2503      TUK != Sema::TUK_Reference) {
2504    Diag(Tok, diag::err_enum_template);
2505
2506    // Skip the rest of this declarator, up until the comma or semicolon.
2507    SkipUntil(tok::comma, true);
2508    return;
2509  }
2510
2511  if (!Name && TUK != Sema::TUK_Definition) {
2512    Diag(Tok, diag::err_enumerator_unnamed_no_def);
2513
2514    // Skip the rest of this declarator, up until the comma or semicolon.
2515    SkipUntil(tok::comma, true);
2516    return;
2517  }
2518
2519  bool Owned = false;
2520  bool IsDependent = false;
2521  const char *PrevSpec = 0;
2522  unsigned DiagID;
2523  Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
2524                                   StartLoc, SS, Name, NameLoc, attrs.getList(),
2525                                   AS,
2526                                   MultiTemplateParamsArg(Actions),
2527                                   Owned, IsDependent, IsScopedEnum,
2528                                   IsScopedUsingClassTag, BaseType);
2529
2530  if (IsDependent) {
2531    // This enum has a dependent nested-name-specifier. Handle it as a
2532    // dependent tag.
2533    if (!Name) {
2534      DS.SetTypeSpecError();
2535      Diag(Tok, diag::err_expected_type_name_after_typename);
2536      return;
2537    }
2538
2539    TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
2540                                                TUK, SS, Name, StartLoc,
2541                                                NameLoc);
2542    if (Type.isInvalid()) {
2543      DS.SetTypeSpecError();
2544      return;
2545    }
2546
2547    if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
2548                           NameLoc.isValid() ? NameLoc : StartLoc,
2549                           PrevSpec, DiagID, Type.get()))
2550      Diag(StartLoc, DiagID) << PrevSpec;
2551
2552    return;
2553  }
2554
2555  if (!TagDecl) {
2556    // The action failed to produce an enumeration tag. If this is a
2557    // definition, consume the entire definition.
2558    if (Tok.is(tok::l_brace)) {
2559      ConsumeBrace();
2560      SkipUntil(tok::r_brace);
2561    }
2562
2563    DS.SetTypeSpecError();
2564    return;
2565  }
2566
2567  if (Tok.is(tok::l_brace))
2568    ParseEnumBody(StartLoc, TagDecl);
2569
2570  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
2571                         NameLoc.isValid() ? NameLoc : StartLoc,
2572                         PrevSpec, DiagID, TagDecl, Owned))
2573    Diag(StartLoc, DiagID) << PrevSpec;
2574}
2575
2576/// ParseEnumBody - Parse a {} enclosed enumerator-list.
2577///       enumerator-list:
2578///         enumerator
2579///         enumerator-list ',' enumerator
2580///       enumerator:
2581///         enumeration-constant
2582///         enumeration-constant '=' constant-expression
2583///       enumeration-constant:
2584///         identifier
2585///
2586void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
2587  // Enter the scope of the enum body and start the definition.
2588  ParseScope EnumScope(this, Scope::DeclScope);
2589  Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
2590
2591  SourceLocation LBraceLoc = ConsumeBrace();
2592
2593  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
2594  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
2595    Diag(Tok, diag::error_empty_enum);
2596
2597  llvm::SmallVector<Decl *, 32> EnumConstantDecls;
2598
2599  Decl *LastEnumConstDecl = 0;
2600
2601  // Parse the enumerator-list.
2602  while (Tok.is(tok::identifier)) {
2603    IdentifierInfo *Ident = Tok.getIdentifierInfo();
2604    SourceLocation IdentLoc = ConsumeToken();
2605
2606    // If attributes exist after the enumerator, parse them.
2607    ParsedAttributes attrs(AttrFactory);
2608    MaybeParseGNUAttributes(attrs);
2609
2610    SourceLocation EqualLoc;
2611    ExprResult AssignedVal;
2612    if (Tok.is(tok::equal)) {
2613      EqualLoc = ConsumeToken();
2614      AssignedVal = ParseConstantExpression();
2615      if (AssignedVal.isInvalid())
2616        SkipUntil(tok::comma, tok::r_brace, true, true);
2617    }
2618
2619    // Install the enumerator constant into EnumDecl.
2620    Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
2621                                                    LastEnumConstDecl,
2622                                                    IdentLoc, Ident,
2623                                                    attrs.getList(), EqualLoc,
2624                                                    AssignedVal.release());
2625    EnumConstantDecls.push_back(EnumConstDecl);
2626    LastEnumConstDecl = EnumConstDecl;
2627
2628    if (Tok.is(tok::identifier)) {
2629      // We're missing a comma between enumerators.
2630      SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2631      Diag(Loc, diag::err_enumerator_list_missing_comma)
2632        << FixItHint::CreateInsertion(Loc, ", ");
2633      continue;
2634    }
2635
2636    if (Tok.isNot(tok::comma))
2637      break;
2638    SourceLocation CommaLoc = ConsumeToken();
2639
2640    if (Tok.isNot(tok::identifier) &&
2641        !(getLang().C99 || getLang().CPlusPlus0x))
2642      Diag(CommaLoc, diag::ext_enumerator_list_comma)
2643        << getLang().CPlusPlus
2644        << FixItHint::CreateRemoval(CommaLoc);
2645  }
2646
2647  // Eat the }.
2648  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2649
2650  // If attributes exist after the identifier list, parse them.
2651  ParsedAttributes attrs(AttrFactory);
2652  MaybeParseGNUAttributes(attrs);
2653
2654  Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
2655                        EnumConstantDecls.data(), EnumConstantDecls.size(),
2656                        getCurScope(), attrs.getList());
2657
2658  EnumScope.Exit();
2659  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, RBraceLoc);
2660}
2661
2662/// isTypeSpecifierQualifier - Return true if the current token could be the
2663/// start of a type-qualifier-list.
2664bool Parser::isTypeQualifier() const {
2665  switch (Tok.getKind()) {
2666  default: return false;
2667
2668    // type-qualifier only in OpenCL
2669  case tok::kw_private:
2670    return getLang().OpenCL;
2671
2672    // type-qualifier
2673  case tok::kw_const:
2674  case tok::kw_volatile:
2675  case tok::kw_restrict:
2676  case tok::kw___private:
2677  case tok::kw___local:
2678  case tok::kw___global:
2679  case tok::kw___constant:
2680  case tok::kw___read_only:
2681  case tok::kw___read_write:
2682  case tok::kw___write_only:
2683    return true;
2684  }
2685}
2686
2687/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2688/// is definitely a type-specifier.  Return false if it isn't part of a type
2689/// specifier or if we're not sure.
2690bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
2691  switch (Tok.getKind()) {
2692  default: return false;
2693    // type-specifiers
2694  case tok::kw_short:
2695  case tok::kw_long:
2696  case tok::kw_signed:
2697  case tok::kw_unsigned:
2698  case tok::kw__Complex:
2699  case tok::kw__Imaginary:
2700  case tok::kw_void:
2701  case tok::kw_char:
2702  case tok::kw_wchar_t:
2703  case tok::kw_char16_t:
2704  case tok::kw_char32_t:
2705  case tok::kw_int:
2706  case tok::kw_float:
2707  case tok::kw_double:
2708  case tok::kw_bool:
2709  case tok::kw__Bool:
2710  case tok::kw__Decimal32:
2711  case tok::kw__Decimal64:
2712  case tok::kw__Decimal128:
2713  case tok::kw___vector:
2714
2715    // struct-or-union-specifier (C99) or class-specifier (C++)
2716  case tok::kw_class:
2717  case tok::kw_struct:
2718  case tok::kw_union:
2719    // enum-specifier
2720  case tok::kw_enum:
2721
2722    // typedef-name
2723  case tok::annot_typename:
2724    return true;
2725  }
2726}
2727
2728/// isTypeSpecifierQualifier - Return true if the current token could be the
2729/// start of a specifier-qualifier-list.
2730bool Parser::isTypeSpecifierQualifier() {
2731  switch (Tok.getKind()) {
2732  default: return false;
2733
2734  case tok::identifier:   // foo::bar
2735    if (TryAltiVecVectorToken())
2736      return true;
2737    // Fall through.
2738  case tok::kw_typename:  // typename T::type
2739    // Annotate typenames and C++ scope specifiers.  If we get one, just
2740    // recurse to handle whatever we get.
2741    if (TryAnnotateTypeOrScopeToken())
2742      return true;
2743    if (Tok.is(tok::identifier))
2744      return false;
2745    return isTypeSpecifierQualifier();
2746
2747  case tok::coloncolon:   // ::foo::bar
2748    if (NextToken().is(tok::kw_new) ||    // ::new
2749        NextToken().is(tok::kw_delete))   // ::delete
2750      return false;
2751
2752    if (TryAnnotateTypeOrScopeToken())
2753      return true;
2754    return isTypeSpecifierQualifier();
2755
2756    // GNU attributes support.
2757  case tok::kw___attribute:
2758    // GNU typeof support.
2759  case tok::kw_typeof:
2760
2761    // type-specifiers
2762  case tok::kw_short:
2763  case tok::kw_long:
2764  case tok::kw_signed:
2765  case tok::kw_unsigned:
2766  case tok::kw__Complex:
2767  case tok::kw__Imaginary:
2768  case tok::kw_void:
2769  case tok::kw_char:
2770  case tok::kw_wchar_t:
2771  case tok::kw_char16_t:
2772  case tok::kw_char32_t:
2773  case tok::kw_int:
2774  case tok::kw_float:
2775  case tok::kw_double:
2776  case tok::kw_bool:
2777  case tok::kw__Bool:
2778  case tok::kw__Decimal32:
2779  case tok::kw__Decimal64:
2780  case tok::kw__Decimal128:
2781  case tok::kw___vector:
2782
2783    // struct-or-union-specifier (C99) or class-specifier (C++)
2784  case tok::kw_class:
2785  case tok::kw_struct:
2786  case tok::kw_union:
2787    // enum-specifier
2788  case tok::kw_enum:
2789
2790    // type-qualifier
2791  case tok::kw_const:
2792  case tok::kw_volatile:
2793  case tok::kw_restrict:
2794
2795    // typedef-name
2796  case tok::annot_typename:
2797    return true;
2798
2799    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2800  case tok::less:
2801    return getLang().ObjC1;
2802
2803  case tok::kw___cdecl:
2804  case tok::kw___stdcall:
2805  case tok::kw___fastcall:
2806  case tok::kw___thiscall:
2807  case tok::kw___w64:
2808  case tok::kw___ptr64:
2809  case tok::kw___pascal:
2810
2811  case tok::kw___private:
2812  case tok::kw___local:
2813  case tok::kw___global:
2814  case tok::kw___constant:
2815  case tok::kw___read_only:
2816  case tok::kw___read_write:
2817  case tok::kw___write_only:
2818
2819    return true;
2820
2821  case tok::kw_private:
2822    return getLang().OpenCL;
2823  }
2824}
2825
2826/// isDeclarationSpecifier() - Return true if the current token is part of a
2827/// declaration specifier.
2828///
2829/// \param DisambiguatingWithExpression True to indicate that the purpose of
2830/// this check is to disambiguate between an expression and a declaration.
2831bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
2832  switch (Tok.getKind()) {
2833  default: return false;
2834
2835  case tok::kw_private:
2836    return getLang().OpenCL;
2837
2838  case tok::identifier:   // foo::bar
2839    // Unfortunate hack to support "Class.factoryMethod" notation.
2840    if (getLang().ObjC1 && NextToken().is(tok::period))
2841      return false;
2842    if (TryAltiVecVectorToken())
2843      return true;
2844    // Fall through.
2845  case tok::kw_typename: // typename T::type
2846    // Annotate typenames and C++ scope specifiers.  If we get one, just
2847    // recurse to handle whatever we get.
2848    if (TryAnnotateTypeOrScopeToken())
2849      return true;
2850    if (Tok.is(tok::identifier))
2851      return false;
2852
2853    // If we're in Objective-C and we have an Objective-C class type followed
2854    // by an identifier and then either ':' or ']', in a place where an
2855    // expression is permitted, then this is probably a class message send
2856    // missing the initial '['. In this case, we won't consider this to be
2857    // the start of a declaration.
2858    if (DisambiguatingWithExpression &&
2859        isStartOfObjCClassMessageMissingOpenBracket())
2860      return false;
2861
2862    return isDeclarationSpecifier();
2863
2864  case tok::coloncolon:   // ::foo::bar
2865    if (NextToken().is(tok::kw_new) ||    // ::new
2866        NextToken().is(tok::kw_delete))   // ::delete
2867      return false;
2868
2869    // Annotate typenames and C++ scope specifiers.  If we get one, just
2870    // recurse to handle whatever we get.
2871    if (TryAnnotateTypeOrScopeToken())
2872      return true;
2873    return isDeclarationSpecifier();
2874
2875    // storage-class-specifier
2876  case tok::kw_typedef:
2877  case tok::kw_extern:
2878  case tok::kw___private_extern__:
2879  case tok::kw_static:
2880  case tok::kw_auto:
2881  case tok::kw_register:
2882  case tok::kw___thread:
2883
2884    // type-specifiers
2885  case tok::kw_short:
2886  case tok::kw_long:
2887  case tok::kw_signed:
2888  case tok::kw_unsigned:
2889  case tok::kw__Complex:
2890  case tok::kw__Imaginary:
2891  case tok::kw_void:
2892  case tok::kw_char:
2893  case tok::kw_wchar_t:
2894  case tok::kw_char16_t:
2895  case tok::kw_char32_t:
2896
2897  case tok::kw_int:
2898  case tok::kw_float:
2899  case tok::kw_double:
2900  case tok::kw_bool:
2901  case tok::kw__Bool:
2902  case tok::kw__Decimal32:
2903  case tok::kw__Decimal64:
2904  case tok::kw__Decimal128:
2905  case tok::kw___vector:
2906
2907    // struct-or-union-specifier (C99) or class-specifier (C++)
2908  case tok::kw_class:
2909  case tok::kw_struct:
2910  case tok::kw_union:
2911    // enum-specifier
2912  case tok::kw_enum:
2913
2914    // type-qualifier
2915  case tok::kw_const:
2916  case tok::kw_volatile:
2917  case tok::kw_restrict:
2918
2919    // function-specifier
2920  case tok::kw_inline:
2921  case tok::kw_virtual:
2922  case tok::kw_explicit:
2923
2924    // typedef-name
2925  case tok::annot_typename:
2926
2927    // static_assert-declaration
2928  case tok::kw__Static_assert:
2929
2930    // GNU typeof support.
2931  case tok::kw_typeof:
2932
2933    // GNU attributes.
2934  case tok::kw___attribute:
2935    return true;
2936
2937    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2938  case tok::less:
2939    return getLang().ObjC1;
2940
2941  case tok::kw___declspec:
2942  case tok::kw___cdecl:
2943  case tok::kw___stdcall:
2944  case tok::kw___fastcall:
2945  case tok::kw___thiscall:
2946  case tok::kw___w64:
2947  case tok::kw___ptr64:
2948  case tok::kw___forceinline:
2949  case tok::kw___pascal:
2950
2951  case tok::kw___private:
2952  case tok::kw___local:
2953  case tok::kw___global:
2954  case tok::kw___constant:
2955  case tok::kw___read_only:
2956  case tok::kw___read_write:
2957  case tok::kw___write_only:
2958
2959    return true;
2960  }
2961}
2962
2963bool Parser::isConstructorDeclarator() {
2964  TentativeParsingAction TPA(*this);
2965
2966  // Parse the C++ scope specifier.
2967  CXXScopeSpec SS;
2968  if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) {
2969    TPA.Revert();
2970    return false;
2971  }
2972
2973  // Parse the constructor name.
2974  if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
2975    // We already know that we have a constructor name; just consume
2976    // the token.
2977    ConsumeToken();
2978  } else {
2979    TPA.Revert();
2980    return false;
2981  }
2982
2983  // Current class name must be followed by a left parentheses.
2984  if (Tok.isNot(tok::l_paren)) {
2985    TPA.Revert();
2986    return false;
2987  }
2988  ConsumeParen();
2989
2990  // A right parentheses or ellipsis signals that we have a constructor.
2991  if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
2992    TPA.Revert();
2993    return true;
2994  }
2995
2996  // If we need to, enter the specified scope.
2997  DeclaratorScopeObj DeclScopeObj(*this, SS);
2998  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2999    DeclScopeObj.EnterDeclaratorScope();
3000
3001  // Optionally skip Microsoft attributes.
3002  ParsedAttributes Attrs(AttrFactory);
3003  MaybeParseMicrosoftAttributes(Attrs);
3004
3005  // Check whether the next token(s) are part of a declaration
3006  // specifier, in which case we have the start of a parameter and,
3007  // therefore, we know that this is a constructor.
3008  bool IsConstructor = isDeclarationSpecifier();
3009  TPA.Revert();
3010  return IsConstructor;
3011}
3012
3013/// ParseTypeQualifierListOpt
3014///          type-qualifier-list: [C99 6.7.5]
3015///            type-qualifier
3016/// [vendor]   attributes
3017///              [ only if VendorAttributesAllowed=true ]
3018///            type-qualifier-list type-qualifier
3019/// [vendor]   type-qualifier-list attributes
3020///              [ only if VendorAttributesAllowed=true ]
3021/// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
3022///              [ only if CXX0XAttributesAllowed=true ]
3023/// Note: vendor can be GNU, MS, etc.
3024///
3025void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
3026                                       bool VendorAttributesAllowed,
3027                                       bool CXX0XAttributesAllowed) {
3028  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3029    SourceLocation Loc = Tok.getLocation();
3030    ParsedAttributesWithRange attrs(AttrFactory);
3031    ParseCXX0XAttributes(attrs);
3032    if (CXX0XAttributesAllowed)
3033      DS.takeAttributesFrom(attrs);
3034    else
3035      Diag(Loc, diag::err_attributes_not_allowed);
3036  }
3037
3038  SourceLocation EndLoc;
3039
3040  while (1) {
3041    bool isInvalid = false;
3042    const char *PrevSpec = 0;
3043    unsigned DiagID = 0;
3044    SourceLocation Loc = Tok.getLocation();
3045
3046    switch (Tok.getKind()) {
3047    case tok::code_completion:
3048      Actions.CodeCompleteTypeQualifiers(DS);
3049      ConsumeCodeCompletionToken();
3050      break;
3051
3052    case tok::kw_const:
3053      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
3054                                 getLang());
3055      break;
3056    case tok::kw_volatile:
3057      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3058                                 getLang());
3059      break;
3060    case tok::kw_restrict:
3061      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3062                                 getLang());
3063      break;
3064
3065    // OpenCL qualifiers:
3066    case tok::kw_private:
3067      if (!getLang().OpenCL)
3068        goto DoneWithTypeQuals;
3069    case tok::kw___private:
3070    case tok::kw___global:
3071    case tok::kw___local:
3072    case tok::kw___constant:
3073    case tok::kw___read_only:
3074    case tok::kw___write_only:
3075    case tok::kw___read_write:
3076      ParseOpenCLQualifiers(DS);
3077      break;
3078
3079    case tok::kw___w64:
3080    case tok::kw___ptr64:
3081    case tok::kw___cdecl:
3082    case tok::kw___stdcall:
3083    case tok::kw___fastcall:
3084    case tok::kw___thiscall:
3085      if (VendorAttributesAllowed) {
3086        ParseMicrosoftTypeAttributes(DS.getAttributes());
3087        continue;
3088      }
3089      goto DoneWithTypeQuals;
3090    case tok::kw___pascal:
3091      if (VendorAttributesAllowed) {
3092        ParseBorlandTypeAttributes(DS.getAttributes());
3093        continue;
3094      }
3095      goto DoneWithTypeQuals;
3096    case tok::kw___attribute:
3097      if (VendorAttributesAllowed) {
3098        ParseGNUAttributes(DS.getAttributes());
3099        continue; // do *not* consume the next token!
3100      }
3101      // otherwise, FALL THROUGH!
3102    default:
3103      DoneWithTypeQuals:
3104      // If this is not a type-qualifier token, we're done reading type
3105      // qualifiers.  First verify that DeclSpec's are consistent.
3106      DS.Finish(Diags, PP);
3107      if (EndLoc.isValid())
3108        DS.SetRangeEnd(EndLoc);
3109      return;
3110    }
3111
3112    // If the specifier combination wasn't legal, issue a diagnostic.
3113    if (isInvalid) {
3114      assert(PrevSpec && "Method did not return previous specifier!");
3115      Diag(Tok, DiagID) << PrevSpec;
3116    }
3117    EndLoc = ConsumeToken();
3118  }
3119}
3120
3121
3122/// ParseDeclarator - Parse and verify a newly-initialized declarator.
3123///
3124void Parser::ParseDeclarator(Declarator &D) {
3125  /// This implements the 'declarator' production in the C grammar, then checks
3126  /// for well-formedness and issues diagnostics.
3127  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3128}
3129
3130/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
3131/// is parsed by the function passed to it. Pass null, and the direct-declarator
3132/// isn't parsed at all, making this function effectively parse the C++
3133/// ptr-operator production.
3134///
3135///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
3136/// [C]     pointer[opt] direct-declarator
3137/// [C++]   direct-declarator
3138/// [C++]   ptr-operator declarator
3139///
3140///       pointer: [C99 6.7.5]
3141///         '*' type-qualifier-list[opt]
3142///         '*' type-qualifier-list[opt] pointer
3143///
3144///       ptr-operator:
3145///         '*' cv-qualifier-seq[opt]
3146///         '&'
3147/// [C++0x] '&&'
3148/// [GNU]   '&' restrict[opt] attributes[opt]
3149/// [GNU?]  '&&' restrict[opt] attributes[opt]
3150///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
3151void Parser::ParseDeclaratorInternal(Declarator &D,
3152                                     DirectDeclParseFunction DirectDeclParser) {
3153  if (Diags.hasAllExtensionsSilenced())
3154    D.setExtension();
3155
3156  // C++ member pointers start with a '::' or a nested-name.
3157  // Member pointers get special handling, since there's no place for the
3158  // scope spec in the generic path below.
3159  if (getLang().CPlusPlus &&
3160      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
3161       Tok.is(tok::annot_cxxscope))) {
3162    CXXScopeSpec SS;
3163    ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true); // ignore fail
3164
3165    if (SS.isNotEmpty()) {
3166      if (Tok.isNot(tok::star)) {
3167        // The scope spec really belongs to the direct-declarator.
3168        D.getCXXScopeSpec() = SS;
3169        if (DirectDeclParser)
3170          (this->*DirectDeclParser)(D);
3171        return;
3172      }
3173
3174      SourceLocation Loc = ConsumeToken();
3175      D.SetRangeEnd(Loc);
3176      DeclSpec DS(AttrFactory);
3177      ParseTypeQualifierListOpt(DS);
3178      D.ExtendWithDeclSpec(DS);
3179
3180      // Recurse to parse whatever is left.
3181      ParseDeclaratorInternal(D, DirectDeclParser);
3182
3183      // Sema will have to catch (syntactically invalid) pointers into global
3184      // scope. It has to catch pointers into namespace scope anyway.
3185      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
3186                                                      Loc),
3187                    DS.getAttributes(),
3188                    /* Don't replace range end. */SourceLocation());
3189      return;
3190    }
3191  }
3192
3193  tok::TokenKind Kind = Tok.getKind();
3194  // Not a pointer, C++ reference, or block.
3195  if (Kind != tok::star && Kind != tok::caret &&
3196      (Kind != tok::amp || !getLang().CPlusPlus) &&
3197      // We parse rvalue refs in C++03, because otherwise the errors are scary.
3198      (Kind != tok::ampamp || !getLang().CPlusPlus)) {
3199    if (DirectDeclParser)
3200      (this->*DirectDeclParser)(D);
3201    return;
3202  }
3203
3204  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
3205  // '&&' -> rvalue reference
3206  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
3207  D.SetRangeEnd(Loc);
3208
3209  if (Kind == tok::star || Kind == tok::caret) {
3210    // Is a pointer.
3211    DeclSpec DS(AttrFactory);
3212
3213    ParseTypeQualifierListOpt(DS);
3214    D.ExtendWithDeclSpec(DS);
3215
3216    // Recursively parse the declarator.
3217    ParseDeclaratorInternal(D, DirectDeclParser);
3218    if (Kind == tok::star)
3219      // Remember that we parsed a pointer type, and remember the type-quals.
3220      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
3221                                                DS.getConstSpecLoc(),
3222                                                DS.getVolatileSpecLoc(),
3223                                                DS.getRestrictSpecLoc()),
3224                    DS.getAttributes(),
3225                    SourceLocation());
3226    else
3227      // Remember that we parsed a Block type, and remember the type-quals.
3228      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
3229                                                     Loc),
3230                    DS.getAttributes(),
3231                    SourceLocation());
3232  } else {
3233    // Is a reference
3234    DeclSpec DS(AttrFactory);
3235
3236    // Complain about rvalue references in C++03, but then go on and build
3237    // the declarator.
3238    if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
3239      Diag(Loc, diag::ext_rvalue_reference);
3240
3241    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
3242    // cv-qualifiers are introduced through the use of a typedef or of a
3243    // template type argument, in which case the cv-qualifiers are ignored.
3244    //
3245    // [GNU] Retricted references are allowed.
3246    // [GNU] Attributes on references are allowed.
3247    // [C++0x] Attributes on references are not allowed.
3248    ParseTypeQualifierListOpt(DS, true, false);
3249    D.ExtendWithDeclSpec(DS);
3250
3251    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
3252      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3253        Diag(DS.getConstSpecLoc(),
3254             diag::err_invalid_reference_qualifier_application) << "const";
3255      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3256        Diag(DS.getVolatileSpecLoc(),
3257             diag::err_invalid_reference_qualifier_application) << "volatile";
3258    }
3259
3260    // Recursively parse the declarator.
3261    ParseDeclaratorInternal(D, DirectDeclParser);
3262
3263    if (D.getNumTypeObjects() > 0) {
3264      // C++ [dcl.ref]p4: There shall be no references to references.
3265      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
3266      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
3267        if (const IdentifierInfo *II = D.getIdentifier())
3268          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3269           << II;
3270        else
3271          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3272            << "type name";
3273
3274        // Once we've complained about the reference-to-reference, we
3275        // can go ahead and build the (technically ill-formed)
3276        // declarator: reference collapsing will take care of it.
3277      }
3278    }
3279
3280    // Remember that we parsed a reference type. It doesn't have type-quals.
3281    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
3282                                                Kind == tok::amp),
3283                  DS.getAttributes(),
3284                  SourceLocation());
3285  }
3286}
3287
3288/// ParseDirectDeclarator
3289///       direct-declarator: [C99 6.7.5]
3290/// [C99]   identifier
3291///         '(' declarator ')'
3292/// [GNU]   '(' attributes declarator ')'
3293/// [C90]   direct-declarator '[' constant-expression[opt] ']'
3294/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3295/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3296/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3297/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
3298///         direct-declarator '(' parameter-type-list ')'
3299///         direct-declarator '(' identifier-list[opt] ')'
3300/// [GNU]   direct-declarator '(' parameter-forward-declarations
3301///                    parameter-type-list[opt] ')'
3302/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
3303///                    cv-qualifier-seq[opt] exception-specification[opt]
3304/// [C++]   declarator-id
3305///
3306///       declarator-id: [C++ 8]
3307///         '...'[opt] id-expression
3308///         '::'[opt] nested-name-specifier[opt] type-name
3309///
3310///       id-expression: [C++ 5.1]
3311///         unqualified-id
3312///         qualified-id
3313///
3314///       unqualified-id: [C++ 5.1]
3315///         identifier
3316///         operator-function-id
3317///         conversion-function-id
3318///          '~' class-name
3319///         template-id
3320///
3321void Parser::ParseDirectDeclarator(Declarator &D) {
3322  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
3323
3324  if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
3325    // ParseDeclaratorInternal might already have parsed the scope.
3326    if (D.getCXXScopeSpec().isEmpty()) {
3327      ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), true);
3328    }
3329
3330    if (D.getCXXScopeSpec().isValid()) {
3331      if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3332        // Change the declaration context for name lookup, until this function
3333        // is exited (and the declarator has been parsed).
3334        DeclScopeObj.EnterDeclaratorScope();
3335    }
3336
3337    // C++0x [dcl.fct]p14:
3338    //   There is a syntactic ambiguity when an ellipsis occurs at the end
3339    //   of a parameter-declaration-clause without a preceding comma. In
3340    //   this case, the ellipsis is parsed as part of the
3341    //   abstract-declarator if the type of the parameter names a template
3342    //   parameter pack that has not been expanded; otherwise, it is parsed
3343    //   as part of the parameter-declaration-clause.
3344    if (Tok.is(tok::ellipsis) &&
3345        !((D.getContext() == Declarator::PrototypeContext ||
3346           D.getContext() == Declarator::BlockLiteralContext) &&
3347          NextToken().is(tok::r_paren) &&
3348          !Actions.containsUnexpandedParameterPacks(D)))
3349      D.setEllipsisLoc(ConsumeToken());
3350
3351    if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
3352        Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
3353      // We found something that indicates the start of an unqualified-id.
3354      // Parse that unqualified-id.
3355      bool AllowConstructorName;
3356      if (D.getDeclSpec().hasTypeSpecifier())
3357        AllowConstructorName = false;
3358      else if (D.getCXXScopeSpec().isSet())
3359        AllowConstructorName =
3360          (D.getContext() == Declarator::FileContext ||
3361           (D.getContext() == Declarator::MemberContext &&
3362            D.getDeclSpec().isFriendSpecified()));
3363      else
3364        AllowConstructorName = (D.getContext() == Declarator::MemberContext);
3365
3366      if (ParseUnqualifiedId(D.getCXXScopeSpec(),
3367                             /*EnteringContext=*/true,
3368                             /*AllowDestructorName=*/true,
3369                             AllowConstructorName,
3370                             ParsedType(),
3371                             D.getName()) ||
3372          // Once we're past the identifier, if the scope was bad, mark the
3373          // whole declarator bad.
3374          D.getCXXScopeSpec().isInvalid()) {
3375        D.SetIdentifier(0, Tok.getLocation());
3376        D.setInvalidType(true);
3377      } else {
3378        // Parsed the unqualified-id; update range information and move along.
3379        if (D.getSourceRange().getBegin().isInvalid())
3380          D.SetRangeBegin(D.getName().getSourceRange().getBegin());
3381        D.SetRangeEnd(D.getName().getSourceRange().getEnd());
3382      }
3383      goto PastIdentifier;
3384    }
3385  } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
3386    assert(!getLang().CPlusPlus &&
3387           "There's a C++-specific check for tok::identifier above");
3388    assert(Tok.getIdentifierInfo() && "Not an identifier?");
3389    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
3390    ConsumeToken();
3391    goto PastIdentifier;
3392  }
3393
3394  if (Tok.is(tok::l_paren)) {
3395    // direct-declarator: '(' declarator ')'
3396    // direct-declarator: '(' attributes declarator ')'
3397    // Example: 'char (*X)'   or 'int (*XX)(void)'
3398    ParseParenDeclarator(D);
3399
3400    // If the declarator was parenthesized, we entered the declarator
3401    // scope when parsing the parenthesized declarator, then exited
3402    // the scope already. Re-enter the scope, if we need to.
3403    if (D.getCXXScopeSpec().isSet()) {
3404      // If there was an error parsing parenthesized declarator, declarator
3405      // scope may have been enterred before. Don't do it again.
3406      if (!D.isInvalidType() &&
3407          Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3408        // Change the declaration context for name lookup, until this function
3409        // is exited (and the declarator has been parsed).
3410        DeclScopeObj.EnterDeclaratorScope();
3411    }
3412  } else if (D.mayOmitIdentifier()) {
3413    // This could be something simple like "int" (in which case the declarator
3414    // portion is empty), if an abstract-declarator is allowed.
3415    D.SetIdentifier(0, Tok.getLocation());
3416  } else {
3417    if (D.getContext() == Declarator::MemberContext)
3418      Diag(Tok, diag::err_expected_member_name_or_semi)
3419        << D.getDeclSpec().getSourceRange();
3420    else if (getLang().CPlusPlus)
3421      Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
3422    else
3423      Diag(Tok, diag::err_expected_ident_lparen);
3424    D.SetIdentifier(0, Tok.getLocation());
3425    D.setInvalidType(true);
3426  }
3427
3428 PastIdentifier:
3429  assert(D.isPastIdentifier() &&
3430         "Haven't past the location of the identifier yet?");
3431
3432  // Don't parse attributes unless we have an identifier.
3433  if (D.getIdentifier())
3434    MaybeParseCXX0XAttributes(D);
3435
3436  while (1) {
3437    if (Tok.is(tok::l_paren)) {
3438      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
3439      // In such a case, check if we actually have a function declarator; if it
3440      // is not, the declarator has been fully parsed.
3441      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
3442        // When not in file scope, warn for ambiguous function declarators, just
3443        // in case the author intended it as a variable definition.
3444        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
3445        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
3446          break;
3447      }
3448      ParsedAttributes attrs(AttrFactory);
3449      ParseFunctionDeclarator(ConsumeParen(), D, attrs);
3450    } else if (Tok.is(tok::l_square)) {
3451      ParseBracketDeclarator(D);
3452    } else {
3453      break;
3454    }
3455  }
3456}
3457
3458/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
3459/// only called before the identifier, so these are most likely just grouping
3460/// parens for precedence.  If we find that these are actually function
3461/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
3462///
3463///       direct-declarator:
3464///         '(' declarator ')'
3465/// [GNU]   '(' attributes declarator ')'
3466///         direct-declarator '(' parameter-type-list ')'
3467///         direct-declarator '(' identifier-list[opt] ')'
3468/// [GNU]   direct-declarator '(' parameter-forward-declarations
3469///                    parameter-type-list[opt] ')'
3470///
3471void Parser::ParseParenDeclarator(Declarator &D) {
3472  SourceLocation StartLoc = ConsumeParen();
3473  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
3474
3475  // Eat any attributes before we look at whether this is a grouping or function
3476  // declarator paren.  If this is a grouping paren, the attribute applies to
3477  // the type being built up, for example:
3478  //     int (__attribute__(()) *x)(long y)
3479  // If this ends up not being a grouping paren, the attribute applies to the
3480  // first argument, for example:
3481  //     int (__attribute__(()) int x)
3482  // In either case, we need to eat any attributes to be able to determine what
3483  // sort of paren this is.
3484  //
3485  ParsedAttributes attrs(AttrFactory);
3486  bool RequiresArg = false;
3487  if (Tok.is(tok::kw___attribute)) {
3488    ParseGNUAttributes(attrs);
3489
3490    // We require that the argument list (if this is a non-grouping paren) be
3491    // present even if the attribute list was empty.
3492    RequiresArg = true;
3493  }
3494  // Eat any Microsoft extensions.
3495  if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
3496       Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
3497       Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64)) {
3498    ParseMicrosoftTypeAttributes(attrs);
3499  }
3500  // Eat any Borland extensions.
3501  if  (Tok.is(tok::kw___pascal))
3502    ParseBorlandTypeAttributes(attrs);
3503
3504  // If we haven't past the identifier yet (or where the identifier would be
3505  // stored, if this is an abstract declarator), then this is probably just
3506  // grouping parens. However, if this could be an abstract-declarator, then
3507  // this could also be the start of function arguments (consider 'void()').
3508  bool isGrouping;
3509
3510  if (!D.mayOmitIdentifier()) {
3511    // If this can't be an abstract-declarator, this *must* be a grouping
3512    // paren, because we haven't seen the identifier yet.
3513    isGrouping = true;
3514  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
3515             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
3516             isDeclarationSpecifier()) {       // 'int(int)' is a function.
3517    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
3518    // considered to be a type, not a K&R identifier-list.
3519    isGrouping = false;
3520  } else {
3521    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
3522    isGrouping = true;
3523  }
3524
3525  // If this is a grouping paren, handle:
3526  // direct-declarator: '(' declarator ')'
3527  // direct-declarator: '(' attributes declarator ')'
3528  if (isGrouping) {
3529    bool hadGroupingParens = D.hasGroupingParens();
3530    D.setGroupingParens(true);
3531
3532    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3533    // Match the ')'.
3534    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, StartLoc);
3535    D.AddTypeInfo(DeclaratorChunk::getParen(StartLoc, EndLoc),
3536                  attrs, EndLoc);
3537
3538    D.setGroupingParens(hadGroupingParens);
3539    return;
3540  }
3541
3542  // Okay, if this wasn't a grouping paren, it must be the start of a function
3543  // argument list.  Recognize that this declarator will never have an
3544  // identifier (and remember where it would have been), then call into
3545  // ParseFunctionDeclarator to handle of argument list.
3546  D.SetIdentifier(0, Tok.getLocation());
3547
3548  ParseFunctionDeclarator(StartLoc, D, attrs, RequiresArg);
3549}
3550
3551/// ParseFunctionDeclarator - We are after the identifier and have parsed the
3552/// declarator D up to a paren, which indicates that we are parsing function
3553/// arguments.
3554///
3555/// If AttrList is non-null, then the caller parsed those arguments immediately
3556/// after the open paren - they should be considered to be the first argument of
3557/// a parameter.  If RequiresArg is true, then the first argument of the
3558/// function is required to be present and required to not be an identifier
3559/// list.
3560///
3561/// This method also handles this portion of the grammar:
3562///       parameter-type-list: [C99 6.7.5]
3563///         parameter-list
3564///         parameter-list ',' '...'
3565/// [C++]   parameter-list '...'
3566///
3567///       parameter-list: [C99 6.7.5]
3568///         parameter-declaration
3569///         parameter-list ',' parameter-declaration
3570///
3571///       parameter-declaration: [C99 6.7.5]
3572///         declaration-specifiers declarator
3573/// [C++]   declaration-specifiers declarator '=' assignment-expression
3574/// [GNU]   declaration-specifiers declarator attributes
3575///         declaration-specifiers abstract-declarator[opt]
3576/// [C++]   declaration-specifiers abstract-declarator[opt]
3577///           '=' assignment-expression
3578/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
3579///
3580/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]",
3581/// C++0x "ref-qualifier[opt]" and "exception-specification[opt]".
3582///
3583/// [C++0x] exception-specification:
3584///           dynamic-exception-specification
3585///           noexcept-specification
3586///
3587void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
3588                                     ParsedAttributes &attrs,
3589                                     bool RequiresArg) {
3590  // lparen is already consumed!
3591  assert(D.isPastIdentifier() && "Should not call before identifier!");
3592
3593  ParsedType TrailingReturnType;
3594
3595  // This parameter list may be empty.
3596  if (Tok.is(tok::r_paren)) {
3597    if (RequiresArg)
3598      Diag(Tok, diag::err_argument_required_after_attribute);
3599
3600    SourceLocation EndLoc = ConsumeParen();  // Eat the closing ')'.
3601
3602    // cv-qualifier-seq[opt].
3603    DeclSpec DS(AttrFactory);
3604    SourceLocation RefQualifierLoc;
3605    bool RefQualifierIsLValueRef = true;
3606    ExceptionSpecificationType ESpecType = EST_None;
3607    SourceRange ESpecRange;
3608    llvm::SmallVector<ParsedType, 2> DynamicExceptions;
3609    llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
3610    ExprResult NoexceptExpr;
3611    if (getLang().CPlusPlus) {
3612      MaybeParseCXX0XAttributes(attrs);
3613
3614      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3615      if (!DS.getSourceRange().getEnd().isInvalid())
3616        EndLoc = DS.getSourceRange().getEnd();
3617
3618      // Parse ref-qualifier[opt]
3619      if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
3620        if (!getLang().CPlusPlus0x)
3621          Diag(Tok, diag::ext_ref_qualifier);
3622
3623        RefQualifierIsLValueRef = Tok.is(tok::amp);
3624        RefQualifierLoc = ConsumeToken();
3625        EndLoc = RefQualifierLoc;
3626      }
3627
3628      // Parse exception-specification[opt].
3629      ESpecType = MaybeParseExceptionSpecification(ESpecRange,
3630                                                   DynamicExceptions,
3631                                                   DynamicExceptionRanges,
3632                                                   NoexceptExpr);
3633      if (ESpecType != EST_None)
3634        EndLoc = ESpecRange.getEnd();
3635
3636      // Parse trailing-return-type.
3637      if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
3638        TrailingReturnType = ParseTrailingReturnType().get();
3639      }
3640    }
3641
3642    // Remember that we parsed a function type, and remember the attributes.
3643    // int() -> no prototype, no '...'.
3644    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
3645                                               /*variadic*/ false,
3646                                               SourceLocation(),
3647                                               /*arglist*/ 0, 0,
3648                                               DS.getTypeQualifiers(),
3649                                               RefQualifierIsLValueRef,
3650                                               RefQualifierLoc,
3651                                               ESpecType, ESpecRange.getBegin(),
3652                                               DynamicExceptions.data(),
3653                                               DynamicExceptionRanges.data(),
3654                                               DynamicExceptions.size(),
3655                                               NoexceptExpr.isUsable() ?
3656                                                 NoexceptExpr.get() : 0,
3657                                               LParenLoc, EndLoc, D,
3658                                               TrailingReturnType),
3659                  attrs, EndLoc);
3660    return;
3661  }
3662
3663  // Alternatively, this parameter list may be an identifier list form for a
3664  // K&R-style function:  void foo(a,b,c)
3665  if (!getLang().CPlusPlus && Tok.is(tok::identifier)
3666      && !TryAltiVecVectorToken()) {
3667    if (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) {
3668      // K&R identifier lists can't have typedefs as identifiers, per
3669      // C99 6.7.5.3p11.
3670      if (RequiresArg)
3671        Diag(Tok, diag::err_argument_required_after_attribute);
3672
3673      // Identifier list.  Note that '(' identifier-list ')' is only allowed for
3674      // normal declarators, not for abstract-declarators.  Get the first
3675      // identifier.
3676      Token FirstTok = Tok;
3677      ConsumeToken();  // eat the first identifier.
3678
3679      // Identifier lists follow a really simple grammar: the identifiers can
3680      // be followed *only* by a ", moreidentifiers" or ")".  However, K&R
3681      // identifier lists are really rare in the brave new modern world, and it
3682      // is very common for someone to typo a type in a non-k&r style list.  If
3683      // we are presented with something like: "void foo(intptr x, float y)",
3684      // we don't want to start parsing the function declarator as though it is
3685      // a K&R style declarator just because intptr is an invalid type.
3686      //
3687      // To handle this, we check to see if the token after the first identifier
3688      // is a "," or ")".  Only if so, do we parse it as an identifier list.
3689      if (Tok.is(tok::comma) || Tok.is(tok::r_paren))
3690        return ParseFunctionDeclaratorIdentifierList(LParenLoc,
3691                                                   FirstTok.getIdentifierInfo(),
3692                                                     FirstTok.getLocation(), D);
3693
3694      // If we get here, the code is invalid.  Push the first identifier back
3695      // into the token stream and parse the first argument as an (invalid)
3696      // normal argument declarator.
3697      PP.EnterToken(Tok);
3698      Tok = FirstTok;
3699    }
3700  }
3701
3702  // Finally, a normal, non-empty parameter type list.
3703
3704  // Build up an array of information about the parsed arguments.
3705  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3706
3707  // Enter function-declaration scope, limiting any declarators to the
3708  // function prototype scope, including parameter declarators.
3709  ParseScope PrototypeScope(this,
3710                            Scope::FunctionPrototypeScope|Scope::DeclScope);
3711
3712  bool IsVariadic = false;
3713  SourceLocation EllipsisLoc;
3714  while (1) {
3715    if (Tok.is(tok::ellipsis)) {
3716      IsVariadic = true;
3717      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
3718      break;
3719    }
3720
3721    // Parse the declaration-specifiers.
3722    // Just use the ParsingDeclaration "scope" of the declarator.
3723    DeclSpec DS(AttrFactory);
3724
3725    // Skip any Microsoft attributes before a param.
3726    if (getLang().Microsoft && Tok.is(tok::l_square))
3727      ParseMicrosoftAttributes(DS.getAttributes());
3728
3729    SourceLocation DSStart = Tok.getLocation();
3730
3731    // If the caller parsed attributes for the first argument, add them now.
3732    // Take them so that we only apply the attributes to the first parameter.
3733    DS.takeAttributesFrom(attrs);
3734
3735    ParseDeclarationSpecifiers(DS);
3736
3737    // Parse the declarator.  This is "PrototypeContext", because we must
3738    // accept either 'declarator' or 'abstract-declarator' here.
3739    Declarator ParmDecl(DS, Declarator::PrototypeContext);
3740    ParseDeclarator(ParmDecl);
3741
3742    // Parse GNU attributes, if present.
3743    MaybeParseGNUAttributes(ParmDecl);
3744
3745    // Remember this parsed parameter in ParamInfo.
3746    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
3747
3748    // DefArgToks is used when the parsing of default arguments needs
3749    // to be delayed.
3750    CachedTokens *DefArgToks = 0;
3751
3752    // If no parameter was specified, verify that *something* was specified,
3753    // otherwise we have a missing type and identifier.
3754    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
3755        ParmDecl.getNumTypeObjects() == 0) {
3756      // Completely missing, emit error.
3757      Diag(DSStart, diag::err_missing_param);
3758    } else {
3759      // Otherwise, we have something.  Add it and let semantic analysis try
3760      // to grok it and add the result to the ParamInfo we are building.
3761
3762      // Inform the actions module about the parameter declarator, so it gets
3763      // added to the current scope.
3764      Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
3765
3766      // Parse the default argument, if any. We parse the default
3767      // arguments in all dialects; the semantic analysis in
3768      // ActOnParamDefaultArgument will reject the default argument in
3769      // C.
3770      if (Tok.is(tok::equal)) {
3771        SourceLocation EqualLoc = Tok.getLocation();
3772
3773        // Parse the default argument
3774        if (D.getContext() == Declarator::MemberContext) {
3775          // If we're inside a class definition, cache the tokens
3776          // corresponding to the default argument. We'll actually parse
3777          // them when we see the end of the class definition.
3778          // FIXME: Templates will require something similar.
3779          // FIXME: Can we use a smart pointer for Toks?
3780          DefArgToks = new CachedTokens;
3781
3782          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
3783                                    /*StopAtSemi=*/true,
3784                                    /*ConsumeFinalToken=*/false)) {
3785            delete DefArgToks;
3786            DefArgToks = 0;
3787            Actions.ActOnParamDefaultArgumentError(Param);
3788          } else {
3789            // Mark the end of the default argument so that we know when to
3790            // stop when we parse it later on.
3791            Token DefArgEnd;
3792            DefArgEnd.startToken();
3793            DefArgEnd.setKind(tok::cxx_defaultarg_end);
3794            DefArgEnd.setLocation(Tok.getLocation());
3795            DefArgToks->push_back(DefArgEnd);
3796            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
3797                                                (*DefArgToks)[1].getLocation());
3798          }
3799        } else {
3800          // Consume the '='.
3801          ConsumeToken();
3802
3803          // The argument isn't actually potentially evaluated unless it is
3804          // used.
3805          EnterExpressionEvaluationContext Eval(Actions,
3806                                              Sema::PotentiallyEvaluatedIfUsed);
3807
3808          ExprResult DefArgResult(ParseAssignmentExpression());
3809          if (DefArgResult.isInvalid()) {
3810            Actions.ActOnParamDefaultArgumentError(Param);
3811            SkipUntil(tok::comma, tok::r_paren, true, true);
3812          } else {
3813            // Inform the actions module about the default argument
3814            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
3815                                              DefArgResult.take());
3816          }
3817        }
3818      }
3819
3820      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3821                                          ParmDecl.getIdentifierLoc(), Param,
3822                                          DefArgToks));
3823    }
3824
3825    // If the next token is a comma, consume it and keep reading arguments.
3826    if (Tok.isNot(tok::comma)) {
3827      if (Tok.is(tok::ellipsis)) {
3828        IsVariadic = true;
3829        EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
3830
3831        if (!getLang().CPlusPlus) {
3832          // We have ellipsis without a preceding ',', which is ill-formed
3833          // in C. Complain and provide the fix.
3834          Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
3835            << FixItHint::CreateInsertion(EllipsisLoc, ", ");
3836        }
3837      }
3838
3839      break;
3840    }
3841
3842    // Consume the comma.
3843    ConsumeToken();
3844  }
3845
3846  // If we have the closing ')', eat it.
3847  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3848
3849  DeclSpec DS(AttrFactory);
3850  SourceLocation RefQualifierLoc;
3851  bool RefQualifierIsLValueRef = true;
3852  ExceptionSpecificationType ESpecType = EST_None;
3853  SourceRange ESpecRange;
3854  llvm::SmallVector<ParsedType, 2> DynamicExceptions;
3855  llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
3856  ExprResult NoexceptExpr;
3857
3858  if (getLang().CPlusPlus) {
3859    MaybeParseCXX0XAttributes(attrs);
3860
3861    // Parse cv-qualifier-seq[opt].
3862    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3863      if (!DS.getSourceRange().getEnd().isInvalid())
3864        EndLoc = DS.getSourceRange().getEnd();
3865
3866    // Parse ref-qualifier[opt]
3867    if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
3868      if (!getLang().CPlusPlus0x)
3869        Diag(Tok, diag::ext_ref_qualifier);
3870
3871      RefQualifierIsLValueRef = Tok.is(tok::amp);
3872      RefQualifierLoc = ConsumeToken();
3873      EndLoc = RefQualifierLoc;
3874    }
3875
3876    // FIXME: We should leave the prototype scope before parsing the exception
3877    // specification, and then reenter it when parsing the trailing return type.
3878    // FIXMEFIXME: Why? That wouldn't be right for the noexcept clause.
3879
3880    // Parse exception-specification[opt].
3881    ESpecType = MaybeParseExceptionSpecification(ESpecRange,
3882                                                 DynamicExceptions,
3883                                                 DynamicExceptionRanges,
3884                                                 NoexceptExpr);
3885    if (ESpecType != EST_None)
3886      EndLoc = ESpecRange.getEnd();
3887
3888    // Parse trailing-return-type.
3889    if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
3890      TrailingReturnType = ParseTrailingReturnType().get();
3891    }
3892  }
3893
3894  // Leave prototype scope.
3895  PrototypeScope.Exit();
3896
3897  // Remember that we parsed a function type, and remember the attributes.
3898  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
3899                                             EllipsisLoc,
3900                                             ParamInfo.data(), ParamInfo.size(),
3901                                             DS.getTypeQualifiers(),
3902                                             RefQualifierIsLValueRef,
3903                                             RefQualifierLoc,
3904                                             ESpecType, ESpecRange.getBegin(),
3905                                             DynamicExceptions.data(),
3906                                             DynamicExceptionRanges.data(),
3907                                             DynamicExceptions.size(),
3908                                             NoexceptExpr.isUsable() ?
3909                                               NoexceptExpr.get() : 0,
3910                                             LParenLoc, EndLoc, D,
3911                                             TrailingReturnType),
3912                attrs, EndLoc);
3913}
3914
3915/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
3916/// we found a K&R-style identifier list instead of a type argument list.  The
3917/// first identifier has already been consumed, and the current token is the
3918/// token right after it.
3919///
3920///       identifier-list: [C99 6.7.5]
3921///         identifier
3922///         identifier-list ',' identifier
3923///
3924void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
3925                                                   IdentifierInfo *FirstIdent,
3926                                                   SourceLocation FirstIdentLoc,
3927                                                   Declarator &D) {
3928  // Build up an array of information about the parsed arguments.
3929  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3930  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
3931
3932  // If there was no identifier specified for the declarator, either we are in
3933  // an abstract-declarator, or we are in a parameter declarator which was found
3934  // to be abstract.  In abstract-declarators, identifier lists are not valid:
3935  // diagnose this.
3936  if (!D.getIdentifier())
3937    Diag(FirstIdentLoc, diag::ext_ident_list_in_param);
3938
3939  // The first identifier was already read, and is known to be the first
3940  // identifier in the list.  Remember this identifier in ParamInfo.
3941  ParamsSoFar.insert(FirstIdent);
3942  ParamInfo.push_back(DeclaratorChunk::ParamInfo(FirstIdent, FirstIdentLoc, 0));
3943
3944  while (Tok.is(tok::comma)) {
3945    // Eat the comma.
3946    ConsumeToken();
3947
3948    // If this isn't an identifier, report the error and skip until ')'.
3949    if (Tok.isNot(tok::identifier)) {
3950      Diag(Tok, diag::err_expected_ident);
3951      SkipUntil(tok::r_paren);
3952      return;
3953    }
3954
3955    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
3956
3957    // Reject 'typedef int y; int test(x, y)', but continue parsing.
3958    if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
3959      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
3960
3961    // Verify that the argument identifier has not already been mentioned.
3962    if (!ParamsSoFar.insert(ParmII)) {
3963      Diag(Tok, diag::err_param_redefinition) << ParmII;
3964    } else {
3965      // Remember this identifier in ParamInfo.
3966      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3967                                                     Tok.getLocation(),
3968                                                     0));
3969    }
3970
3971    // Eat the identifier.
3972    ConsumeToken();
3973  }
3974
3975  // If we have the closing ')', eat it and we're done.
3976  SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3977
3978  // Remember that we parsed a function type, and remember the attributes.  This
3979  // function type is always a K&R style function type, which is not varargs and
3980  // has no prototype.
3981  ParsedAttributes attrs(AttrFactory);
3982  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
3983                                             SourceLocation(),
3984                                             &ParamInfo[0], ParamInfo.size(),
3985                                             /*TypeQuals*/0,
3986                                             true, SourceLocation(),
3987                                             EST_None, SourceLocation(), 0, 0,
3988                                             0, 0, LParenLoc, RLoc, D),
3989                attrs, RLoc);
3990}
3991
3992/// [C90]   direct-declarator '[' constant-expression[opt] ']'
3993/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3994/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3995/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3996/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
3997void Parser::ParseBracketDeclarator(Declarator &D) {
3998  SourceLocation StartLoc = ConsumeBracket();
3999
4000  // C array syntax has many features, but by-far the most common is [] and [4].
4001  // This code does a fast path to handle some of the most obvious cases.
4002  if (Tok.getKind() == tok::r_square) {
4003    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4004    ParsedAttributes attrs(AttrFactory);
4005    MaybeParseCXX0XAttributes(attrs);
4006
4007    // Remember that we parsed the empty array type.
4008    ExprResult NumElements;
4009    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
4010                                            StartLoc, EndLoc),
4011                  attrs, EndLoc);
4012    return;
4013  } else if (Tok.getKind() == tok::numeric_constant &&
4014             GetLookAheadToken(1).is(tok::r_square)) {
4015    // [4] is very common.  Parse the numeric constant expression.
4016    ExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
4017    ConsumeToken();
4018
4019    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4020    ParsedAttributes attrs(AttrFactory);
4021    MaybeParseCXX0XAttributes(attrs);
4022
4023    // Remember that we parsed a array type, and remember its features.
4024    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
4025                                            ExprRes.release(),
4026                                            StartLoc, EndLoc),
4027                  attrs, EndLoc);
4028    return;
4029  }
4030
4031  // If valid, this location is the position where we read the 'static' keyword.
4032  SourceLocation StaticLoc;
4033  if (Tok.is(tok::kw_static))
4034    StaticLoc = ConsumeToken();
4035
4036  // If there is a type-qualifier-list, read it now.
4037  // Type qualifiers in an array subscript are a C99 feature.
4038  DeclSpec DS(AttrFactory);
4039  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
4040
4041  // If we haven't already read 'static', check to see if there is one after the
4042  // type-qualifier-list.
4043  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
4044    StaticLoc = ConsumeToken();
4045
4046  // Handle "direct-declarator [ type-qual-list[opt] * ]".
4047  bool isStar = false;
4048  ExprResult NumElements;
4049
4050  // Handle the case where we have '[*]' as the array size.  However, a leading
4051  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
4052  // the the token after the star is a ']'.  Since stars in arrays are
4053  // infrequent, use of lookahead is not costly here.
4054  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
4055    ConsumeToken();  // Eat the '*'.
4056
4057    if (StaticLoc.isValid()) {
4058      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
4059      StaticLoc = SourceLocation();  // Drop the static.
4060    }
4061    isStar = true;
4062  } else if (Tok.isNot(tok::r_square)) {
4063    // Note, in C89, this production uses the constant-expr production instead
4064    // of assignment-expr.  The only difference is that assignment-expr allows
4065    // things like '=' and '*='.  Sema rejects these in C89 mode because they
4066    // are not i-c-e's, so we don't need to distinguish between the two here.
4067
4068    // Parse the constant-expression or assignment-expression now (depending
4069    // on dialect).
4070    if (getLang().CPlusPlus)
4071      NumElements = ParseConstantExpression();
4072    else
4073      NumElements = ParseAssignmentExpression();
4074  }
4075
4076  // If there was an error parsing the assignment-expression, recover.
4077  if (NumElements.isInvalid()) {
4078    D.setInvalidType(true);
4079    // If the expression was invalid, skip it.
4080    SkipUntil(tok::r_square);
4081    return;
4082  }
4083
4084  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4085
4086  ParsedAttributes attrs(AttrFactory);
4087  MaybeParseCXX0XAttributes(attrs);
4088
4089  // Remember that we parsed a array type, and remember its features.
4090  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
4091                                          StaticLoc.isValid(), isStar,
4092                                          NumElements.release(),
4093                                          StartLoc, EndLoc),
4094                attrs, EndLoc);
4095}
4096
4097/// [GNU]   typeof-specifier:
4098///           typeof ( expressions )
4099///           typeof ( type-name )
4100/// [GNU/C++] typeof unary-expression
4101///
4102void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
4103  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
4104  Token OpTok = Tok;
4105  SourceLocation StartLoc = ConsumeToken();
4106
4107  const bool hasParens = Tok.is(tok::l_paren);
4108
4109  bool isCastExpr;
4110  ParsedType CastTy;
4111  SourceRange CastRange;
4112  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
4113                                                          CastTy, CastRange);
4114  if (hasParens)
4115    DS.setTypeofParensRange(CastRange);
4116
4117  if (CastRange.getEnd().isInvalid())
4118    // FIXME: Not accurate, the range gets one token more than it should.
4119    DS.SetRangeEnd(Tok.getLocation());
4120  else
4121    DS.SetRangeEnd(CastRange.getEnd());
4122
4123  if (isCastExpr) {
4124    if (!CastTy) {
4125      DS.SetTypeSpecError();
4126      return;
4127    }
4128
4129    const char *PrevSpec = 0;
4130    unsigned DiagID;
4131    // Check for duplicate type specifiers (e.g. "int typeof(int)").
4132    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
4133                           DiagID, CastTy))
4134      Diag(StartLoc, DiagID) << PrevSpec;
4135    return;
4136  }
4137
4138  // If we get here, the operand to the typeof was an expresion.
4139  if (Operand.isInvalid()) {
4140    DS.SetTypeSpecError();
4141    return;
4142  }
4143
4144  const char *PrevSpec = 0;
4145  unsigned DiagID;
4146  // Check for duplicate type specifiers (e.g. "int typeof(int)").
4147  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
4148                         DiagID, Operand.get()))
4149    Diag(StartLoc, DiagID) << PrevSpec;
4150}
4151
4152
4153/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
4154/// from TryAltiVecVectorToken.
4155bool Parser::TryAltiVecVectorTokenOutOfLine() {
4156  Token Next = NextToken();
4157  switch (Next.getKind()) {
4158  default: return false;
4159  case tok::kw_short:
4160  case tok::kw_long:
4161  case tok::kw_signed:
4162  case tok::kw_unsigned:
4163  case tok::kw_void:
4164  case tok::kw_char:
4165  case tok::kw_int:
4166  case tok::kw_float:
4167  case tok::kw_double:
4168  case tok::kw_bool:
4169  case tok::kw___pixel:
4170    Tok.setKind(tok::kw___vector);
4171    return true;
4172  case tok::identifier:
4173    if (Next.getIdentifierInfo() == Ident_pixel) {
4174      Tok.setKind(tok::kw___vector);
4175      return true;
4176    }
4177    return false;
4178  }
4179}
4180
4181bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
4182                                      const char *&PrevSpec, unsigned &DiagID,
4183                                      bool &isInvalid) {
4184  if (Tok.getIdentifierInfo() == Ident_vector) {
4185    Token Next = NextToken();
4186    switch (Next.getKind()) {
4187    case tok::kw_short:
4188    case tok::kw_long:
4189    case tok::kw_signed:
4190    case tok::kw_unsigned:
4191    case tok::kw_void:
4192    case tok::kw_char:
4193    case tok::kw_int:
4194    case tok::kw_float:
4195    case tok::kw_double:
4196    case tok::kw_bool:
4197    case tok::kw___pixel:
4198      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4199      return true;
4200    case tok::identifier:
4201      if (Next.getIdentifierInfo() == Ident_pixel) {
4202        isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4203        return true;
4204      }
4205      break;
4206    default:
4207      break;
4208    }
4209  } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
4210             DS.isTypeAltiVecVector()) {
4211    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
4212    return true;
4213  }
4214  return false;
4215}
4216