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