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