ParseDecl.cpp revision 9ab14541716928894821cf5d53d6b4c95ffdf3a3
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/Parse/Scope.h"
17#include "clang/Parse/Template.h"
18#include "RAIIObjectsForParser.h"
19#include "llvm/ADT/SmallSet.h"
20using namespace clang;
21
22//===----------------------------------------------------------------------===//
23// C99 6.7: Declarations.
24//===----------------------------------------------------------------------===//
25
26/// ParseTypeName
27///       type-name: [C99 6.7.6]
28///         specifier-qualifier-list abstract-declarator[opt]
29///
30/// Called type-id in C++.
31Action::TypeResult Parser::ParseTypeName(SourceRange *Range) {
32  // Parse the common declaration-specifiers piece.
33  DeclSpec DS;
34  ParseSpecifierQualifierList(DS);
35
36  // Parse the abstract-declarator, if present.
37  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
38  ParseDeclarator(DeclaratorInfo);
39  if (Range)
40    *Range = DeclaratorInfo.getSourceRange();
41
42  if (DeclaratorInfo.isInvalidType())
43    return true;
44
45  return Actions.ActOnTypeName(CurScope, DeclaratorInfo);
46}
47
48/// ParseGNUAttributes - Parse a non-empty attributes list.
49///
50/// [GNU] attributes:
51///         attribute
52///         attributes attribute
53///
54/// [GNU]  attribute:
55///          '__attribute__' '(' '(' attribute-list ')' ')'
56///
57/// [GNU]  attribute-list:
58///          attrib
59///          attribute_list ',' attrib
60///
61/// [GNU]  attrib:
62///          empty
63///          attrib-name
64///          attrib-name '(' identifier ')'
65///          attrib-name '(' identifier ',' nonempty-expr-list ')'
66///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
67///
68/// [GNU]  attrib-name:
69///          identifier
70///          typespec
71///          typequal
72///          storageclass
73///
74/// FIXME: The GCC grammar/code for this construct implies we need two
75/// token lookahead. Comment from gcc: "If they start with an identifier
76/// which is followed by a comma or close parenthesis, then the arguments
77/// start with that identifier; otherwise they are an expression list."
78///
79/// At the moment, I am not doing 2 token lookahead. I am also unaware of
80/// any attributes that don't work (based on my limited testing). Most
81/// attributes are very simple in practice. Until we find a bug, I don't see
82/// a pressing need to implement the 2 token lookahead.
83
84AttributeList *Parser::ParseGNUAttributes(SourceLocation *EndLoc) {
85  assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
86
87  AttributeList *CurrAttr = 0;
88
89  while (Tok.is(tok::kw___attribute)) {
90    ConsumeToken();
91    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
92                         "attribute")) {
93      SkipUntil(tok::r_paren, true); // skip until ) or ;
94      return CurrAttr;
95    }
96    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
97      SkipUntil(tok::r_paren, true); // skip until ) or ;
98      return CurrAttr;
99    }
100    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
101    while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
102           Tok.is(tok::comma)) {
103
104      if (Tok.is(tok::comma)) {
105        // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
106        ConsumeToken();
107        continue;
108      }
109      // we have an identifier or declaration specifier (const, int, etc.)
110      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
111      SourceLocation AttrNameLoc = ConsumeToken();
112
113      // check if we have a "parameterized" attribute
114      if (Tok.is(tok::l_paren)) {
115        ConsumeParen(); // ignore the left paren loc for now
116
117        if (Tok.is(tok::identifier)) {
118          IdentifierInfo *ParmName = Tok.getIdentifierInfo();
119          SourceLocation ParmLoc = ConsumeToken();
120
121          if (Tok.is(tok::r_paren)) {
122            // __attribute__(( mode(byte) ))
123            ConsumeParen(); // ignore the right paren loc for now
124            CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc,
125                                         ParmName, ParmLoc, 0, 0, CurrAttr);
126          } else if (Tok.is(tok::comma)) {
127            ConsumeToken();
128            // __attribute__(( format(printf, 1, 2) ))
129            ExprVector ArgExprs(Actions);
130            bool ArgExprsOk = true;
131
132            // now parse the non-empty comma separated list of expressions
133            while (1) {
134              OwningExprResult ArgExpr(ParseAssignmentExpression());
135              if (ArgExpr.isInvalid()) {
136                ArgExprsOk = false;
137                SkipUntil(tok::r_paren);
138                break;
139              } else {
140                ArgExprs.push_back(ArgExpr.release());
141              }
142              if (Tok.isNot(tok::comma))
143                break;
144              ConsumeToken(); // Eat the comma, move to the next argument
145            }
146            if (ArgExprsOk && Tok.is(tok::r_paren)) {
147              ConsumeParen(); // ignore the right paren loc for now
148              CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
149                                           AttrNameLoc, ParmName, ParmLoc,
150                                           ArgExprs.take(), ArgExprs.size(),
151                                           CurrAttr);
152            }
153          }
154        } else { // not an identifier
155          switch (Tok.getKind()) {
156          case tok::r_paren:
157          // parse a possibly empty comma separated list of expressions
158            // __attribute__(( nonnull() ))
159            ConsumeParen(); // ignore the right paren loc for now
160            CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc,
161                                         0, SourceLocation(), 0, 0, CurrAttr);
162            break;
163          case tok::kw_char:
164          case tok::kw_wchar_t:
165          case tok::kw_char16_t:
166          case tok::kw_char32_t:
167          case tok::kw_bool:
168          case tok::kw_short:
169          case tok::kw_int:
170          case tok::kw_long:
171          case tok::kw_signed:
172          case tok::kw_unsigned:
173          case tok::kw_float:
174          case tok::kw_double:
175          case tok::kw_void:
176          case tok::kw_typeof:
177            // If it's a builtin type name, eat it and expect a rparen
178            // __attribute__(( vec_type_hint(char) ))
179            ConsumeToken();
180            CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc,
181                                         0, SourceLocation(), 0, 0, CurrAttr);
182            if (Tok.is(tok::r_paren))
183              ConsumeParen();
184            break;
185          default:
186            // __attribute__(( aligned(16) ))
187            ExprVector ArgExprs(Actions);
188            bool ArgExprsOk = true;
189
190            // now parse the list of expressions
191            while (1) {
192              OwningExprResult ArgExpr(ParseAssignmentExpression());
193              if (ArgExpr.isInvalid()) {
194                ArgExprsOk = false;
195                SkipUntil(tok::r_paren);
196                break;
197              } else {
198                ArgExprs.push_back(ArgExpr.release());
199              }
200              if (Tok.isNot(tok::comma))
201                break;
202              ConsumeToken(); // Eat the comma, move to the next argument
203            }
204            // Match the ')'.
205            if (ArgExprsOk && Tok.is(tok::r_paren)) {
206              ConsumeParen(); // ignore the right paren loc for now
207              CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
208                           AttrNameLoc, 0, SourceLocation(), ArgExprs.take(),
209                           ArgExprs.size(),
210                           CurrAttr);
211            }
212            break;
213          }
214        }
215      } else {
216        CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc,
217                                     0, SourceLocation(), 0, 0, CurrAttr);
218      }
219    }
220    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
221      SkipUntil(tok::r_paren, false);
222    SourceLocation Loc = Tok.getLocation();
223    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
224      SkipUntil(tok::r_paren, false);
225    }
226    if (EndLoc)
227      *EndLoc = Loc;
228  }
229  return CurrAttr;
230}
231
232/// ParseMicrosoftDeclSpec - Parse an __declspec construct
233///
234/// [MS] decl-specifier:
235///             __declspec ( extended-decl-modifier-seq )
236///
237/// [MS] extended-decl-modifier-seq:
238///             extended-decl-modifier[opt]
239///             extended-decl-modifier extended-decl-modifier-seq
240
241AttributeList* Parser::ParseMicrosoftDeclSpec(AttributeList *CurrAttr) {
242  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
243
244  ConsumeToken();
245  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
246                       "declspec")) {
247    SkipUntil(tok::r_paren, true); // skip until ) or ;
248    return CurrAttr;
249  }
250  while (Tok.getIdentifierInfo()) {
251    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
252    SourceLocation AttrNameLoc = ConsumeToken();
253    if (Tok.is(tok::l_paren)) {
254      ConsumeParen();
255      // FIXME: This doesn't parse __declspec(property(get=get_func_name))
256      // correctly.
257      OwningExprResult ArgExpr(ParseAssignmentExpression());
258      if (!ArgExpr.isInvalid()) {
259        ExprTy* ExprList = ArgExpr.take();
260        CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
261                                     SourceLocation(), &ExprList, 1,
262                                     CurrAttr, true);
263      }
264      if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
265        SkipUntil(tok::r_paren, false);
266    } else {
267      CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc,
268                                   0, SourceLocation(), 0, 0, CurrAttr, true);
269    }
270  }
271  if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
272    SkipUntil(tok::r_paren, false);
273  return CurrAttr;
274}
275
276AttributeList* Parser::ParseMicrosoftTypeAttributes(AttributeList *CurrAttr) {
277  // Treat these like attributes
278  // FIXME: Allow Sema to distinguish between these and real attributes!
279  while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
280         Tok.is(tok::kw___cdecl)    || Tok.is(tok::kw___ptr64) ||
281         Tok.is(tok::kw___w64)) {
282    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
283    SourceLocation AttrNameLoc = ConsumeToken();
284    if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64))
285      // FIXME: Support these properly!
286      continue;
287    CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
288                                 SourceLocation(), 0, 0, CurrAttr, true);
289  }
290  return CurrAttr;
291}
292
293/// ParseDeclaration - Parse a full 'declaration', which consists of
294/// declaration-specifiers, some number of declarators, and a semicolon.
295/// 'Context' should be a Declarator::TheContext value.  This returns the
296/// location of the semicolon in DeclEnd.
297///
298///       declaration: [C99 6.7]
299///         block-declaration ->
300///           simple-declaration
301///           others                   [FIXME]
302/// [C++]   template-declaration
303/// [C++]   namespace-definition
304/// [C++]   using-directive
305/// [C++]   using-declaration
306/// [C++0x] static_assert-declaration
307///         others... [FIXME]
308///
309Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
310                                                SourceLocation &DeclEnd,
311                                                CXX0XAttributeList Attr) {
312  DeclPtrTy SingleDecl;
313  switch (Tok.getKind()) {
314  case tok::kw_template:
315  case tok::kw_export:
316    if (Attr.HasAttr)
317      Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
318        << Attr.Range;
319    SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
320    break;
321  case tok::kw_namespace:
322    if (Attr.HasAttr)
323      Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
324        << Attr.Range;
325    SingleDecl = ParseNamespace(Context, DeclEnd);
326    break;
327  case tok::kw_using:
328    SingleDecl = ParseUsingDirectiveOrDeclaration(Context, DeclEnd, Attr);
329    break;
330  case tok::kw_static_assert:
331    if (Attr.HasAttr)
332      Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
333        << Attr.Range;
334    SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
335    break;
336  default:
337    return ParseSimpleDeclaration(Context, DeclEnd, Attr.AttrList, true);
338  }
339
340  // This routine returns a DeclGroup, if the thing we parsed only contains a
341  // single decl, convert it now.
342  return Actions.ConvertDeclToDeclGroup(SingleDecl);
343}
344
345///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
346///         declaration-specifiers init-declarator-list[opt] ';'
347///[C90/C++]init-declarator-list ';'                             [TODO]
348/// [OMP]   threadprivate-directive                              [TODO]
349///
350/// If RequireSemi is false, this does not check for a ';' at the end of the
351/// declaration.  If it is true, it checks for and eats it.
352Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(unsigned Context,
353                                                      SourceLocation &DeclEnd,
354                                                      AttributeList *Attr,
355                                                      bool RequireSemi) {
356  // Parse the common declaration-specifiers piece.
357  ParsingDeclSpec DS(*this);
358  if (Attr)
359    DS.AddAttributes(Attr);
360  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
361                            getDeclSpecContextFromDeclaratorContext(Context));
362
363  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
364  // declaration-specifiers init-declarator-list[opt] ';'
365  if (Tok.is(tok::semi)) {
366    if (RequireSemi) ConsumeToken();
367    DeclPtrTy TheDecl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
368    DS.complete(TheDecl);
369    return Actions.ConvertDeclToDeclGroup(TheDecl);
370  }
371
372  return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd);
373}
374
375/// ParseDeclGroup - Having concluded that this is either a function
376/// definition or a group of object declarations, actually parse the
377/// result.
378Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
379                                              unsigned Context,
380                                              bool AllowFunctionDefinitions,
381                                              SourceLocation *DeclEnd) {
382  // Parse the first declarator.
383  ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
384  ParseDeclarator(D);
385
386  // Bail out if the first declarator didn't seem well-formed.
387  if (!D.hasName() && !D.mayOmitIdentifier()) {
388    // Skip until ; or }.
389    SkipUntil(tok::r_brace, true, true);
390    if (Tok.is(tok::semi))
391      ConsumeToken();
392    return DeclGroupPtrTy();
393  }
394
395  if (AllowFunctionDefinitions && D.isFunctionDeclarator()) {
396    if (isDeclarationAfterDeclarator()) {
397      // Fall though.  We have to check this first, though, because
398      // __attribute__ might be the start of a function definition in
399      // (extended) K&R C.
400    } else if (isStartOfFunctionDefinition()) {
401      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
402        Diag(Tok, diag::err_function_declared_typedef);
403
404        // Recover by treating the 'typedef' as spurious.
405        DS.ClearStorageClassSpecs();
406      }
407
408      DeclPtrTy TheDecl = ParseFunctionDefinition(D);
409      return Actions.ConvertDeclToDeclGroup(TheDecl);
410    } else {
411      Diag(Tok, diag::err_expected_fn_body);
412      SkipUntil(tok::semi);
413      return DeclGroupPtrTy();
414    }
415  }
416
417  llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
418  DeclPtrTy FirstDecl = ParseDeclarationAfterDeclarator(D);
419  D.complete(FirstDecl);
420  if (FirstDecl.get())
421    DeclsInGroup.push_back(FirstDecl);
422
423  // If we don't have a comma, it is either the end of the list (a ';') or an
424  // error, bail out.
425  while (Tok.is(tok::comma)) {
426    // Consume the comma.
427    ConsumeToken();
428
429    // Parse the next declarator.
430    D.clear();
431
432    // Accept attributes in an init-declarator.  In the first declarator in a
433    // declaration, these would be part of the declspec.  In subsequent
434    // declarators, they become part of the declarator itself, so that they
435    // don't apply to declarators after *this* one.  Examples:
436    //    short __attribute__((common)) var;    -> declspec
437    //    short var __attribute__((common));    -> declarator
438    //    short x, __attribute__((common)) var;    -> declarator
439    if (Tok.is(tok::kw___attribute)) {
440      SourceLocation Loc;
441      AttributeList *AttrList = ParseGNUAttributes(&Loc);
442      D.AddAttributes(AttrList, Loc);
443    }
444
445    ParseDeclarator(D);
446
447    DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(D);
448    D.complete(ThisDecl);
449    if (ThisDecl.get())
450      DeclsInGroup.push_back(ThisDecl);
451  }
452
453  if (DeclEnd)
454    *DeclEnd = Tok.getLocation();
455
456  if (Context != Declarator::ForContext &&
457      ExpectAndConsume(tok::semi,
458                       Context == Declarator::FileContext
459                         ? diag::err_invalid_token_after_toplevel_declarator
460                         : diag::err_expected_semi_declaration)) {
461    SkipUntil(tok::r_brace, true, true);
462    if (Tok.is(tok::semi))
463      ConsumeToken();
464  }
465
466  return Actions.FinalizeDeclaratorGroup(CurScope, DS,
467                                         DeclsInGroup.data(),
468                                         DeclsInGroup.size());
469}
470
471/// \brief Parse 'declaration' after parsing 'declaration-specifiers
472/// declarator'. This method parses the remainder of the declaration
473/// (including any attributes or initializer, among other things) and
474/// finalizes the declaration.
475///
476///       init-declarator: [C99 6.7]
477///         declarator
478///         declarator '=' initializer
479/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
480/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
481/// [C++]   declarator initializer[opt]
482///
483/// [C++] initializer:
484/// [C++]   '=' initializer-clause
485/// [C++]   '(' expression-list ')'
486/// [C++0x] '=' 'default'                                                [TODO]
487/// [C++0x] '=' 'delete'
488///
489/// According to the standard grammar, =default and =delete are function
490/// definitions, but that definitely doesn't fit with the parser here.
491///
492Parser::DeclPtrTy Parser::ParseDeclarationAfterDeclarator(Declarator &D,
493                                     const ParsedTemplateInfo &TemplateInfo) {
494  // If a simple-asm-expr is present, parse it.
495  if (Tok.is(tok::kw_asm)) {
496    SourceLocation Loc;
497    OwningExprResult AsmLabel(ParseSimpleAsm(&Loc));
498    if (AsmLabel.isInvalid()) {
499      SkipUntil(tok::semi, true, true);
500      return DeclPtrTy();
501    }
502
503    D.setAsmLabel(AsmLabel.release());
504    D.SetRangeEnd(Loc);
505  }
506
507  // If attributes are present, parse them.
508  if (Tok.is(tok::kw___attribute)) {
509    SourceLocation Loc;
510    AttributeList *AttrList = ParseGNUAttributes(&Loc);
511    D.AddAttributes(AttrList, Loc);
512  }
513
514  // Inform the current actions module that we just parsed this declarator.
515  DeclPtrTy ThisDecl;
516  switch (TemplateInfo.Kind) {
517  case ParsedTemplateInfo::NonTemplate:
518    ThisDecl = Actions.ActOnDeclarator(CurScope, D);
519    break;
520
521  case ParsedTemplateInfo::Template:
522  case ParsedTemplateInfo::ExplicitSpecialization:
523    ThisDecl = Actions.ActOnTemplateDeclarator(CurScope,
524                             Action::MultiTemplateParamsArg(Actions,
525                                          TemplateInfo.TemplateParams->data(),
526                                          TemplateInfo.TemplateParams->size()),
527                                               D);
528    break;
529
530  case ParsedTemplateInfo::ExplicitInstantiation: {
531    Action::DeclResult ThisRes
532      = Actions.ActOnExplicitInstantiation(CurScope,
533                                           TemplateInfo.ExternLoc,
534                                           TemplateInfo.TemplateLoc,
535                                           D);
536    if (ThisRes.isInvalid()) {
537      SkipUntil(tok::semi, true, true);
538      return DeclPtrTy();
539    }
540
541    ThisDecl = ThisRes.get();
542    break;
543    }
544  }
545
546  // Parse declarator '=' initializer.
547  if (Tok.is(tok::equal)) {
548    ConsumeToken();
549    if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
550      SourceLocation DelLoc = ConsumeToken();
551      Actions.SetDeclDeleted(ThisDecl, DelLoc);
552    } else {
553      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
554        EnterScope(0);
555        Actions.ActOnCXXEnterDeclInitializer(CurScope, ThisDecl);
556      }
557
558      OwningExprResult Init(ParseInitializer());
559
560      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
561        Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
562        ExitScope();
563      }
564
565      if (Init.isInvalid()) {
566        SkipUntil(tok::comma, true, true);
567        Actions.ActOnInitializerError(ThisDecl);
568      } else
569        Actions.AddInitializerToDecl(ThisDecl, move(Init));
570    }
571  } else if (Tok.is(tok::l_paren)) {
572    // Parse C++ direct initializer: '(' expression-list ')'
573    SourceLocation LParenLoc = ConsumeParen();
574    ExprVector Exprs(Actions);
575    CommaLocsTy CommaLocs;
576
577    if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
578      EnterScope(0);
579      Actions.ActOnCXXEnterDeclInitializer(CurScope, ThisDecl);
580    }
581
582    if (ParseExpressionList(Exprs, CommaLocs)) {
583      SkipUntil(tok::r_paren);
584
585      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
586        Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
587        ExitScope();
588      }
589    } else {
590      // Match the ')'.
591      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
592
593      assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
594             "Unexpected number of commas!");
595
596      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
597        Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
598        ExitScope();
599      }
600
601      Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc,
602                                            move_arg(Exprs),
603                                            CommaLocs.data(), RParenLoc);
604    }
605  } else {
606    bool TypeContainsUndeducedAuto =
607      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
608    Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsUndeducedAuto);
609  }
610
611  return ThisDecl;
612}
613
614/// ParseSpecifierQualifierList
615///        specifier-qualifier-list:
616///          type-specifier specifier-qualifier-list[opt]
617///          type-qualifier specifier-qualifier-list[opt]
618/// [GNU]    attributes     specifier-qualifier-list[opt]
619///
620void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
621  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
622  /// parse declaration-specifiers and complain about extra stuff.
623  ParseDeclarationSpecifiers(DS);
624
625  // Validate declspec for type-name.
626  unsigned Specs = DS.getParsedSpecifiers();
627  if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
628      !DS.getAttributes())
629    Diag(Tok, diag::err_typename_requires_specqual);
630
631  // Issue diagnostic and remove storage class if present.
632  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
633    if (DS.getStorageClassSpecLoc().isValid())
634      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
635    else
636      Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
637    DS.ClearStorageClassSpecs();
638  }
639
640  // Issue diagnostic and remove function specfier if present.
641  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
642    if (DS.isInlineSpecified())
643      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
644    if (DS.isVirtualSpecified())
645      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
646    if (DS.isExplicitSpecified())
647      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
648    DS.ClearFunctionSpecs();
649  }
650}
651
652/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
653/// specified token is valid after the identifier in a declarator which
654/// immediately follows the declspec.  For example, these things are valid:
655///
656///      int x   [             4];         // direct-declarator
657///      int x   (             int y);     // direct-declarator
658///  int(int x   )                         // direct-declarator
659///      int x   ;                         // simple-declaration
660///      int x   =             17;         // init-declarator-list
661///      int x   ,             y;          // init-declarator-list
662///      int x   __asm__       ("foo");    // init-declarator-list
663///      int x   :             4;          // struct-declarator
664///      int x   {             5};         // C++'0x unified initializers
665///
666/// This is not, because 'x' does not immediately follow the declspec (though
667/// ')' happens to be valid anyway).
668///    int (x)
669///
670static bool isValidAfterIdentifierInDeclarator(const Token &T) {
671  return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
672         T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
673         T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
674}
675
676
677/// ParseImplicitInt - This method is called when we have an non-typename
678/// identifier in a declspec (which normally terminates the decl spec) when
679/// the declspec has no type specifier.  In this case, the declspec is either
680/// malformed or is "implicit int" (in K&R and C89).
681///
682/// This method handles diagnosing this prettily and returns false if the
683/// declspec is done being processed.  If it recovers and thinks there may be
684/// other pieces of declspec after it, it returns true.
685///
686bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
687                              const ParsedTemplateInfo &TemplateInfo,
688                              AccessSpecifier AS) {
689  assert(Tok.is(tok::identifier) && "should have identifier");
690
691  SourceLocation Loc = Tok.getLocation();
692  // If we see an identifier that is not a type name, we normally would
693  // parse it as the identifer being declared.  However, when a typename
694  // is typo'd or the definition is not included, this will incorrectly
695  // parse the typename as the identifier name and fall over misparsing
696  // later parts of the diagnostic.
697  //
698  // As such, we try to do some look-ahead in cases where this would
699  // otherwise be an "implicit-int" case to see if this is invalid.  For
700  // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
701  // an identifier with implicit int, we'd get a parse error because the
702  // next token is obviously invalid for a type.  Parse these as a case
703  // with an invalid type specifier.
704  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
705
706  // Since we know that this either implicit int (which is rare) or an
707  // error, we'd do lookahead to try to do better recovery.
708  if (isValidAfterIdentifierInDeclarator(NextToken())) {
709    // If this token is valid for implicit int, e.g. "static x = 4", then
710    // we just avoid eating the identifier, so it will be parsed as the
711    // identifier in the declarator.
712    return false;
713  }
714
715  // Otherwise, if we don't consume this token, we are going to emit an
716  // error anyway.  Try to recover from various common problems.  Check
717  // to see if this was a reference to a tag name without a tag specified.
718  // This is a common problem in C (saying 'foo' instead of 'struct foo').
719  //
720  // C++ doesn't need this, and isTagName doesn't take SS.
721  if (SS == 0) {
722    const char *TagName = 0;
723    tok::TokenKind TagKind = tok::unknown;
724
725    switch (Actions.isTagName(*Tok.getIdentifierInfo(), CurScope)) {
726      default: break;
727      case DeclSpec::TST_enum:  TagName="enum"  ;TagKind=tok::kw_enum  ;break;
728      case DeclSpec::TST_union: TagName="union" ;TagKind=tok::kw_union ;break;
729      case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break;
730      case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break;
731    }
732
733    if (TagName) {
734      Diag(Loc, diag::err_use_of_tag_name_without_tag)
735        << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus
736        << FixItHint::CreateInsertion(Tok.getLocation(),TagName);
737
738      // Parse this as a tag as if the missing tag were present.
739      if (TagKind == tok::kw_enum)
740        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
741      else
742        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
743      return true;
744    }
745  }
746
747  // This is almost certainly an invalid type name. Let the action emit a
748  // diagnostic and attempt to recover.
749  Action::TypeTy *T = 0;
750  if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
751                                      CurScope, SS, T)) {
752    // The action emitted a diagnostic, so we don't have to.
753    if (T) {
754      // The action has suggested that the type T could be used. Set that as
755      // the type in the declaration specifiers, consume the would-be type
756      // name token, and we're done.
757      const char *PrevSpec;
758      unsigned DiagID;
759      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
760                         false);
761      DS.SetRangeEnd(Tok.getLocation());
762      ConsumeToken();
763
764      // There may be other declaration specifiers after this.
765      return true;
766    }
767
768    // Fall through; the action had no suggestion for us.
769  } else {
770    // The action did not emit a diagnostic, so emit one now.
771    SourceRange R;
772    if (SS) R = SS->getRange();
773    Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
774  }
775
776  // Mark this as an error.
777  const char *PrevSpec;
778  unsigned DiagID;
779  DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
780  DS.SetRangeEnd(Tok.getLocation());
781  ConsumeToken();
782
783  // TODO: Could inject an invalid typedef decl in an enclosing scope to
784  // avoid rippling error messages on subsequent uses of the same type,
785  // could be useful if #include was forgotten.
786  return false;
787}
788
789/// \brief Determine the declaration specifier context from the declarator
790/// context.
791///
792/// \param Context the declarator context, which is one of the
793/// Declarator::TheContext enumerator values.
794Parser::DeclSpecContext
795Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
796  if (Context == Declarator::MemberContext)
797    return DSC_class;
798  if (Context == Declarator::FileContext)
799    return DSC_top_level;
800  return DSC_normal;
801}
802
803/// ParseDeclarationSpecifiers
804///       declaration-specifiers: [C99 6.7]
805///         storage-class-specifier declaration-specifiers[opt]
806///         type-specifier declaration-specifiers[opt]
807/// [C99]   function-specifier declaration-specifiers[opt]
808/// [GNU]   attributes declaration-specifiers[opt]
809///
810///       storage-class-specifier: [C99 6.7.1]
811///         'typedef'
812///         'extern'
813///         'static'
814///         'auto'
815///         'register'
816/// [C++]   'mutable'
817/// [GNU]   '__thread'
818///       function-specifier: [C99 6.7.4]
819/// [C99]   'inline'
820/// [C++]   'virtual'
821/// [C++]   'explicit'
822///       'friend': [C++ dcl.friend]
823///       'constexpr': [C++0x dcl.constexpr]
824
825///
826void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
827                                        const ParsedTemplateInfo &TemplateInfo,
828                                        AccessSpecifier AS,
829                                        DeclSpecContext DSContext) {
830  if (Tok.is(tok::code_completion)) {
831    Action::CodeCompletionContext CCC = Action::CCC_Namespace;
832    if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
833      CCC = DSContext == DSC_class? Action::CCC_MemberTemplate
834                                  : Action::CCC_Template;
835    else if (DSContext == DSC_class)
836      CCC = Action::CCC_Class;
837    else if (ObjCImpDecl)
838      CCC = Action::CCC_ObjCImplementation;
839
840    Actions.CodeCompleteOrdinaryName(CurScope, CCC);
841    ConsumeToken();
842  }
843
844  DS.SetRangeStart(Tok.getLocation());
845  while (1) {
846    bool isInvalid = false;
847    const char *PrevSpec = 0;
848    unsigned DiagID = 0;
849
850    SourceLocation Loc = Tok.getLocation();
851
852    switch (Tok.getKind()) {
853    default:
854    DoneWithDeclSpec:
855      // If this is not a declaration specifier token, we're done reading decl
856      // specifiers.  First verify that DeclSpec's are consistent.
857      DS.Finish(Diags, PP);
858      return;
859
860    case tok::coloncolon: // ::foo::bar
861      // C++ scope specifier.  Annotate and loop, or bail out on error.
862      if (TryAnnotateCXXScopeToken(true)) {
863        if (!DS.hasTypeSpecifier())
864          DS.SetTypeSpecError();
865        goto DoneWithDeclSpec;
866      }
867      if (Tok.is(tok::coloncolon)) // ::new or ::delete
868        goto DoneWithDeclSpec;
869      continue;
870
871    case tok::annot_cxxscope: {
872      if (DS.hasTypeSpecifier())
873        goto DoneWithDeclSpec;
874
875      CXXScopeSpec SS;
876      SS.setScopeRep(Tok.getAnnotationValue());
877      SS.setRange(Tok.getAnnotationRange());
878
879      // We are looking for a qualified typename.
880      Token Next = NextToken();
881      if (Next.is(tok::annot_template_id) &&
882          static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
883            ->Kind == TNK_Type_template) {
884        // We have a qualified template-id, e.g., N::A<int>
885
886        // C++ [class.qual]p2:
887        //   In a lookup in which the constructor is an acceptable lookup
888        //   result and the nested-name-specifier nominates a class C:
889        //
890        //     - if the name specified after the
891        //       nested-name-specifier, when looked up in C, is the
892        //       injected-class-name of C (Clause 9), or
893        //
894        //     - if the name specified after the nested-name-specifier
895        //       is the same as the identifier or the
896        //       simple-template-id's template-name in the last
897        //       component of the nested-name-specifier,
898        //
899        //   the name is instead considered to name the constructor of
900        //   class C.
901        //
902        // Thus, if the template-name is actually the constructor
903        // name, then the code is ill-formed; this interpretation is
904        // reinforced by the NAD status of core issue 635.
905        TemplateIdAnnotation *TemplateId
906          = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue());
907        if (DSContext == DSC_top_level && TemplateId->Name &&
908            Actions.isCurrentClassName(*TemplateId->Name, CurScope, &SS)) {
909          if (isConstructorDeclarator()) {
910            // The user meant this to be an out-of-line constructor
911            // definition, but template arguments are not allowed
912            // there.  Just allow this as a constructor; we'll
913            // complain about it later.
914            goto DoneWithDeclSpec;
915          }
916
917          // The user meant this to name a type, but it actually names
918          // a constructor with some extraneous template
919          // arguments. Complain, then parse it as a type as the user
920          // intended.
921          Diag(TemplateId->TemplateNameLoc,
922               diag::err_out_of_line_template_id_names_constructor)
923            << TemplateId->Name;
924        }
925
926        DS.getTypeSpecScope() = SS;
927        ConsumeToken(); // The C++ scope.
928        assert(Tok.is(tok::annot_template_id) &&
929               "ParseOptionalCXXScopeSpecifier not working");
930        AnnotateTemplateIdTokenAsType(&SS);
931        continue;
932      }
933
934      if (Next.is(tok::annot_typename)) {
935        DS.getTypeSpecScope() = SS;
936        ConsumeToken(); // The C++ scope.
937        if (Tok.getAnnotationValue())
938          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc,
939                                         PrevSpec, DiagID,
940                                         Tok.getAnnotationValue());
941        else
942          DS.SetTypeSpecError();
943        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
944        ConsumeToken(); // The typename
945      }
946
947      if (Next.isNot(tok::identifier))
948        goto DoneWithDeclSpec;
949
950      // If we're in a context where the identifier could be a class name,
951      // check whether this is a constructor declaration.
952      if (DSContext == DSC_top_level &&
953          Actions.isCurrentClassName(*Next.getIdentifierInfo(), CurScope,
954                                     &SS)) {
955        if (isConstructorDeclarator())
956          goto DoneWithDeclSpec;
957
958        // As noted in C++ [class.qual]p2 (cited above), when the name
959        // of the class is qualified in a context where it could name
960        // a constructor, its a constructor name. However, we've
961        // looked at the declarator, and the user probably meant this
962        // to be a type. Complain that it isn't supposed to be treated
963        // as a type, then proceed to parse it as a type.
964        Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
965          << Next.getIdentifierInfo();
966      }
967
968      TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
969                                            Next.getLocation(), CurScope, &SS);
970
971      // If the referenced identifier is not a type, then this declspec is
972      // erroneous: We already checked about that it has no type specifier, and
973      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
974      // typename.
975      if (TypeRep == 0) {
976        ConsumeToken();   // Eat the scope spec so the identifier is current.
977        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
978        goto DoneWithDeclSpec;
979      }
980
981      DS.getTypeSpecScope() = SS;
982      ConsumeToken(); // The C++ scope.
983
984      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
985                                     DiagID, TypeRep);
986      if (isInvalid)
987        break;
988
989      DS.SetRangeEnd(Tok.getLocation());
990      ConsumeToken(); // The typename.
991
992      continue;
993    }
994
995    case tok::annot_typename: {
996      if (Tok.getAnnotationValue())
997        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
998                                       DiagID, Tok.getAnnotationValue());
999      else
1000        DS.SetTypeSpecError();
1001
1002      if (isInvalid)
1003        break;
1004
1005      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1006      ConsumeToken(); // The typename
1007
1008      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1009      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1010      // Objective-C interface.  If we don't have Objective-C or a '<', this is
1011      // just a normal reference to a typedef name.
1012      if (!Tok.is(tok::less) || !getLang().ObjC1)
1013        continue;
1014
1015      SourceLocation LAngleLoc, EndProtoLoc;
1016      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1017      llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1018      ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1019                                  LAngleLoc, EndProtoLoc);
1020      DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1021                               ProtocolLocs.data(), LAngleLoc);
1022
1023      DS.SetRangeEnd(EndProtoLoc);
1024      continue;
1025    }
1026
1027      // typedef-name
1028    case tok::identifier: {
1029      // In C++, check to see if this is a scope specifier like foo::bar::, if
1030      // so handle it as such.  This is important for ctor parsing.
1031      if (getLang().CPlusPlus) {
1032        if (TryAnnotateCXXScopeToken(true)) {
1033          if (!DS.hasTypeSpecifier())
1034            DS.SetTypeSpecError();
1035          goto DoneWithDeclSpec;
1036        }
1037        if (!Tok.is(tok::identifier))
1038          continue;
1039      }
1040
1041      // This identifier can only be a typedef name if we haven't already seen
1042      // a type-specifier.  Without this check we misparse:
1043      //  typedef int X; struct Y { short X; };  as 'short int'.
1044      if (DS.hasTypeSpecifier())
1045        goto DoneWithDeclSpec;
1046
1047      // Check for need to substitute AltiVec keyword tokens.
1048      if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1049        break;
1050
1051      // It has to be available as a typedef too!
1052      TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(),
1053                                            Tok.getLocation(), CurScope);
1054
1055      // If this is not a typedef name, don't parse it as part of the declspec,
1056      // it must be an implicit int or an error.
1057      if (TypeRep == 0) {
1058        if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
1059        goto DoneWithDeclSpec;
1060      }
1061
1062      // If we're in a context where the identifier could be a class name,
1063      // check whether this is a constructor declaration.
1064      if (getLang().CPlusPlus && DSContext == DSC_class &&
1065          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
1066          isConstructorDeclarator())
1067        goto DoneWithDeclSpec;
1068
1069      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1070                                     DiagID, TypeRep);
1071      if (isInvalid)
1072        break;
1073
1074      DS.SetRangeEnd(Tok.getLocation());
1075      ConsumeToken(); // The identifier
1076
1077      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1078      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1079      // Objective-C interface.  If we don't have Objective-C or a '<', this is
1080      // just a normal reference to a typedef name.
1081      if (!Tok.is(tok::less) || !getLang().ObjC1)
1082        continue;
1083
1084      SourceLocation LAngleLoc, EndProtoLoc;
1085      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1086      llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1087      ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1088                                  LAngleLoc, EndProtoLoc);
1089      DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1090                               ProtocolLocs.data(), LAngleLoc);
1091
1092      DS.SetRangeEnd(EndProtoLoc);
1093
1094      // Need to support trailing type qualifiers (e.g. "id<p> const").
1095      // If a type specifier follows, it will be diagnosed elsewhere.
1096      continue;
1097    }
1098
1099      // type-name
1100    case tok::annot_template_id: {
1101      TemplateIdAnnotation *TemplateId
1102        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1103      if (TemplateId->Kind != TNK_Type_template) {
1104        // This template-id does not refer to a type name, so we're
1105        // done with the type-specifiers.
1106        goto DoneWithDeclSpec;
1107      }
1108
1109      // If we're in a context where the template-id could be a
1110      // constructor name or specialization, check whether this is a
1111      // constructor declaration.
1112      if (getLang().CPlusPlus && DSContext == DSC_class &&
1113          Actions.isCurrentClassName(*TemplateId->Name, CurScope) &&
1114          isConstructorDeclarator())
1115        goto DoneWithDeclSpec;
1116
1117      // Turn the template-id annotation token into a type annotation
1118      // token, then try again to parse it as a type-specifier.
1119      AnnotateTemplateIdTokenAsType();
1120      continue;
1121    }
1122
1123    // GNU attributes support.
1124    case tok::kw___attribute:
1125      DS.AddAttributes(ParseGNUAttributes());
1126      continue;
1127
1128    // Microsoft declspec support.
1129    case tok::kw___declspec:
1130      DS.AddAttributes(ParseMicrosoftDeclSpec());
1131      continue;
1132
1133    // Microsoft single token adornments.
1134    case tok::kw___forceinline:
1135      // FIXME: Add handling here!
1136      break;
1137
1138    case tok::kw___ptr64:
1139    case tok::kw___w64:
1140    case tok::kw___cdecl:
1141    case tok::kw___stdcall:
1142    case tok::kw___fastcall:
1143      DS.AddAttributes(ParseMicrosoftTypeAttributes());
1144      continue;
1145
1146    // storage-class-specifier
1147    case tok::kw_typedef:
1148      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
1149                                         DiagID);
1150      break;
1151    case tok::kw_extern:
1152      if (DS.isThreadSpecified())
1153        Diag(Tok, diag::ext_thread_before) << "extern";
1154      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1155                                         DiagID);
1156      break;
1157    case tok::kw___private_extern__:
1158      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1159                                         PrevSpec, DiagID);
1160      break;
1161    case tok::kw_static:
1162      if (DS.isThreadSpecified())
1163        Diag(Tok, diag::ext_thread_before) << "static";
1164      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1165                                         DiagID);
1166      break;
1167    case tok::kw_auto:
1168      if (getLang().CPlusPlus0x)
1169        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1170                                       DiagID);
1171      else
1172        isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1173                                           DiagID);
1174      break;
1175    case tok::kw_register:
1176      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1177                                         DiagID);
1178      break;
1179    case tok::kw_mutable:
1180      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1181                                         DiagID);
1182      break;
1183    case tok::kw___thread:
1184      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1185      break;
1186
1187    // function-specifier
1188    case tok::kw_inline:
1189      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1190      break;
1191    case tok::kw_virtual:
1192      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1193      break;
1194    case tok::kw_explicit:
1195      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1196      break;
1197
1198    // friend
1199    case tok::kw_friend:
1200      if (DSContext == DSC_class)
1201        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1202      else {
1203        PrevSpec = ""; // not actually used by the diagnostic
1204        DiagID = diag::err_friend_invalid_in_context;
1205        isInvalid = true;
1206      }
1207      break;
1208
1209    // constexpr
1210    case tok::kw_constexpr:
1211      isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
1212      break;
1213
1214    // type-specifier
1215    case tok::kw_short:
1216      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1217                                      DiagID);
1218      break;
1219    case tok::kw_long:
1220      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1221        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1222                                        DiagID);
1223      else
1224        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1225                                        DiagID);
1226      break;
1227    case tok::kw_signed:
1228      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1229                                     DiagID);
1230      break;
1231    case tok::kw_unsigned:
1232      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1233                                     DiagID);
1234      break;
1235    case tok::kw__Complex:
1236      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1237                                        DiagID);
1238      break;
1239    case tok::kw__Imaginary:
1240      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1241                                        DiagID);
1242      break;
1243    case tok::kw_void:
1244      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1245                                     DiagID);
1246      break;
1247    case tok::kw_char:
1248      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1249                                     DiagID);
1250      break;
1251    case tok::kw_int:
1252      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1253                                     DiagID);
1254      break;
1255    case tok::kw_float:
1256      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1257                                     DiagID);
1258      break;
1259    case tok::kw_double:
1260      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1261                                     DiagID);
1262      break;
1263    case tok::kw_wchar_t:
1264      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1265                                     DiagID);
1266      break;
1267    case tok::kw_char16_t:
1268      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1269                                     DiagID);
1270      break;
1271    case tok::kw_char32_t:
1272      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1273                                     DiagID);
1274      break;
1275    case tok::kw_bool:
1276    case tok::kw__Bool:
1277      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1278                                     DiagID);
1279      break;
1280    case tok::kw__Decimal32:
1281      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1282                                     DiagID);
1283      break;
1284    case tok::kw__Decimal64:
1285      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1286                                     DiagID);
1287      break;
1288    case tok::kw__Decimal128:
1289      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1290                                     DiagID);
1291      break;
1292    case tok::kw___vector:
1293      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1294      break;
1295    case tok::kw___pixel:
1296      isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1297      break;
1298
1299    // class-specifier:
1300    case tok::kw_class:
1301    case tok::kw_struct:
1302    case tok::kw_union: {
1303      tok::TokenKind Kind = Tok.getKind();
1304      ConsumeToken();
1305      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1306      continue;
1307    }
1308
1309    // enum-specifier:
1310    case tok::kw_enum:
1311      ConsumeToken();
1312      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1313      continue;
1314
1315    // cv-qualifier:
1316    case tok::kw_const:
1317      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1318                                 getLang());
1319      break;
1320    case tok::kw_volatile:
1321      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1322                                 getLang());
1323      break;
1324    case tok::kw_restrict:
1325      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1326                                 getLang());
1327      break;
1328
1329    // C++ typename-specifier:
1330    case tok::kw_typename:
1331      if (TryAnnotateTypeOrScopeToken()) {
1332        DS.SetTypeSpecError();
1333        goto DoneWithDeclSpec;
1334      }
1335      if (!Tok.is(tok::kw_typename))
1336        continue;
1337      break;
1338
1339    // GNU typeof support.
1340    case tok::kw_typeof:
1341      ParseTypeofSpecifier(DS);
1342      continue;
1343
1344    case tok::kw_decltype:
1345      ParseDecltypeSpecifier(DS);
1346      continue;
1347
1348    case tok::less:
1349      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1350      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
1351      // but we support it.
1352      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1353        goto DoneWithDeclSpec;
1354
1355      {
1356        SourceLocation LAngleLoc, EndProtoLoc;
1357        llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1358        llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1359        ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1360                                    LAngleLoc, EndProtoLoc);
1361        DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1362                                 ProtocolLocs.data(), LAngleLoc);
1363        DS.SetRangeEnd(EndProtoLoc);
1364
1365        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1366          << FixItHint::CreateInsertion(Loc, "id")
1367          << SourceRange(Loc, EndProtoLoc);
1368        // Need to support trailing type qualifiers (e.g. "id<p> const").
1369        // If a type specifier follows, it will be diagnosed elsewhere.
1370        continue;
1371      }
1372    }
1373    // If the specifier wasn't legal, issue a diagnostic.
1374    if (isInvalid) {
1375      assert(PrevSpec && "Method did not return previous specifier!");
1376      assert(DiagID);
1377      Diag(Tok, DiagID) << PrevSpec;
1378    }
1379    DS.SetRangeEnd(Tok.getLocation());
1380    ConsumeToken();
1381  }
1382}
1383
1384/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1385/// primarily follow the C++ grammar with additions for C99 and GNU,
1386/// which together subsume the C grammar. Note that the C++
1387/// type-specifier also includes the C type-qualifier (for const,
1388/// volatile, and C99 restrict). Returns true if a type-specifier was
1389/// found (and parsed), false otherwise.
1390///
1391///       type-specifier: [C++ 7.1.5]
1392///         simple-type-specifier
1393///         class-specifier
1394///         enum-specifier
1395///         elaborated-type-specifier  [TODO]
1396///         cv-qualifier
1397///
1398///       cv-qualifier: [C++ 7.1.5.1]
1399///         'const'
1400///         'volatile'
1401/// [C99]   'restrict'
1402///
1403///       simple-type-specifier: [ C++ 7.1.5.2]
1404///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
1405///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
1406///         'char'
1407///         'wchar_t'
1408///         'bool'
1409///         'short'
1410///         'int'
1411///         'long'
1412///         'signed'
1413///         'unsigned'
1414///         'float'
1415///         'double'
1416///         'void'
1417/// [C99]   '_Bool'
1418/// [C99]   '_Complex'
1419/// [C99]   '_Imaginary'  // Removed in TC2?
1420/// [GNU]   '_Decimal32'
1421/// [GNU]   '_Decimal64'
1422/// [GNU]   '_Decimal128'
1423/// [GNU]   typeof-specifier
1424/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
1425/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
1426/// [C++0x] 'decltype' ( expression )
1427/// [AltiVec] '__vector'
1428bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1429                                        const char *&PrevSpec,
1430                                        unsigned &DiagID,
1431                                        const ParsedTemplateInfo &TemplateInfo,
1432                                        bool SuppressDeclarations) {
1433  SourceLocation Loc = Tok.getLocation();
1434
1435  switch (Tok.getKind()) {
1436  case tok::identifier:   // foo::bar
1437    // Check for need to substitute AltiVec keyword tokens.
1438    if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1439      break;
1440    // Fall through.
1441  case tok::kw_typename:  // typename foo::bar
1442    // Annotate typenames and C++ scope specifiers.  If we get one, just
1443    // recurse to handle whatever we get.
1444    if (TryAnnotateTypeOrScopeToken())
1445      return true;
1446    if (Tok.is(tok::identifier))
1447      return false;
1448    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1449                                      TemplateInfo, SuppressDeclarations);
1450  case tok::coloncolon:   // ::foo::bar
1451    if (NextToken().is(tok::kw_new) ||    // ::new
1452        NextToken().is(tok::kw_delete))   // ::delete
1453      return false;
1454
1455    // Annotate typenames and C++ scope specifiers.  If we get one, just
1456    // recurse to handle whatever we get.
1457    if (TryAnnotateTypeOrScopeToken())
1458      return true;
1459    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1460                                      TemplateInfo, SuppressDeclarations);
1461
1462  // simple-type-specifier:
1463  case tok::annot_typename: {
1464    if (Tok.getAnnotationValue())
1465      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1466                                     DiagID, Tok.getAnnotationValue());
1467    else
1468      DS.SetTypeSpecError();
1469    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1470    ConsumeToken(); // The typename
1471
1472    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1473    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1474    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1475    // just a normal reference to a typedef name.
1476    if (!Tok.is(tok::less) || !getLang().ObjC1)
1477      return true;
1478
1479    SourceLocation LAngleLoc, EndProtoLoc;
1480    llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1481    llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1482    ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1483                                LAngleLoc, EndProtoLoc);
1484    DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1485                             ProtocolLocs.data(), LAngleLoc);
1486
1487    DS.SetRangeEnd(EndProtoLoc);
1488    return true;
1489  }
1490
1491  case tok::kw_short:
1492    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1493    break;
1494  case tok::kw_long:
1495    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1496      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1497                                      DiagID);
1498    else
1499      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1500                                      DiagID);
1501    break;
1502  case tok::kw_signed:
1503    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1504    break;
1505  case tok::kw_unsigned:
1506    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1507                                   DiagID);
1508    break;
1509  case tok::kw__Complex:
1510    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1511                                      DiagID);
1512    break;
1513  case tok::kw__Imaginary:
1514    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1515                                      DiagID);
1516    break;
1517  case tok::kw_void:
1518    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1519    break;
1520  case tok::kw_char:
1521    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1522    break;
1523  case tok::kw_int:
1524    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1525    break;
1526  case tok::kw_float:
1527    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1528    break;
1529  case tok::kw_double:
1530    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1531    break;
1532  case tok::kw_wchar_t:
1533    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1534    break;
1535  case tok::kw_char16_t:
1536    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1537    break;
1538  case tok::kw_char32_t:
1539    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1540    break;
1541  case tok::kw_bool:
1542  case tok::kw__Bool:
1543    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1544    break;
1545  case tok::kw__Decimal32:
1546    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1547                                   DiagID);
1548    break;
1549  case tok::kw__Decimal64:
1550    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1551                                   DiagID);
1552    break;
1553  case tok::kw__Decimal128:
1554    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1555                                   DiagID);
1556    break;
1557  case tok::kw___vector:
1558    isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1559    break;
1560  case tok::kw___pixel:
1561    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1562    break;
1563
1564  // class-specifier:
1565  case tok::kw_class:
1566  case tok::kw_struct:
1567  case tok::kw_union: {
1568    tok::TokenKind Kind = Tok.getKind();
1569    ConsumeToken();
1570    ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none,
1571                        SuppressDeclarations);
1572    return true;
1573  }
1574
1575  // enum-specifier:
1576  case tok::kw_enum:
1577    ConsumeToken();
1578    ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none);
1579    return true;
1580
1581  // cv-qualifier:
1582  case tok::kw_const:
1583    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1584                               DiagID, getLang());
1585    break;
1586  case tok::kw_volatile:
1587    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1588                               DiagID, getLang());
1589    break;
1590  case tok::kw_restrict:
1591    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1592                               DiagID, getLang());
1593    break;
1594
1595  // GNU typeof support.
1596  case tok::kw_typeof:
1597    ParseTypeofSpecifier(DS);
1598    return true;
1599
1600  // C++0x decltype support.
1601  case tok::kw_decltype:
1602    ParseDecltypeSpecifier(DS);
1603    return true;
1604
1605  // C++0x auto support.
1606  case tok::kw_auto:
1607    if (!getLang().CPlusPlus0x)
1608      return false;
1609
1610    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
1611    break;
1612  case tok::kw___ptr64:
1613  case tok::kw___w64:
1614  case tok::kw___cdecl:
1615  case tok::kw___stdcall:
1616  case tok::kw___fastcall:
1617    DS.AddAttributes(ParseMicrosoftTypeAttributes());
1618    return true;
1619
1620  default:
1621    // Not a type-specifier; do nothing.
1622    return false;
1623  }
1624
1625  // If the specifier combination wasn't legal, issue a diagnostic.
1626  if (isInvalid) {
1627    assert(PrevSpec && "Method did not return previous specifier!");
1628    // Pick between error or extwarn.
1629    Diag(Tok, DiagID) << PrevSpec;
1630  }
1631  DS.SetRangeEnd(Tok.getLocation());
1632  ConsumeToken(); // whatever we parsed above.
1633  return true;
1634}
1635
1636/// ParseStructDeclaration - Parse a struct declaration without the terminating
1637/// semicolon.
1638///
1639///       struct-declaration:
1640///         specifier-qualifier-list struct-declarator-list
1641/// [GNU]   __extension__ struct-declaration
1642/// [GNU]   specifier-qualifier-list
1643///       struct-declarator-list:
1644///         struct-declarator
1645///         struct-declarator-list ',' struct-declarator
1646/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
1647///       struct-declarator:
1648///         declarator
1649/// [GNU]   declarator attributes[opt]
1650///         declarator[opt] ':' constant-expression
1651/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
1652///
1653void Parser::
1654ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
1655  if (Tok.is(tok::kw___extension__)) {
1656    // __extension__ silences extension warnings in the subexpression.
1657    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1658    ConsumeToken();
1659    return ParseStructDeclaration(DS, Fields);
1660  }
1661
1662  // Parse the common specifier-qualifiers-list piece.
1663  SourceLocation DSStart = Tok.getLocation();
1664  ParseSpecifierQualifierList(DS);
1665
1666  // If there are no declarators, this is a free-standing declaration
1667  // specifier. Let the actions module cope with it.
1668  if (Tok.is(tok::semi)) {
1669    Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1670    return;
1671  }
1672
1673  // Read struct-declarators until we find the semicolon.
1674  bool FirstDeclarator = true;
1675  while (1) {
1676    ParsingDeclRAIIObject PD(*this);
1677    FieldDeclarator DeclaratorInfo(DS);
1678
1679    // Attributes are only allowed here on successive declarators.
1680    if (!FirstDeclarator && Tok.is(tok::kw___attribute)) {
1681      SourceLocation Loc;
1682      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1683      DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1684    }
1685
1686    /// struct-declarator: declarator
1687    /// struct-declarator: declarator[opt] ':' constant-expression
1688    if (Tok.isNot(tok::colon)) {
1689      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1690      ColonProtectionRAIIObject X(*this);
1691      ParseDeclarator(DeclaratorInfo.D);
1692    }
1693
1694    if (Tok.is(tok::colon)) {
1695      ConsumeToken();
1696      OwningExprResult Res(ParseConstantExpression());
1697      if (Res.isInvalid())
1698        SkipUntil(tok::semi, true, true);
1699      else
1700        DeclaratorInfo.BitfieldSize = Res.release();
1701    }
1702
1703    // If attributes exist after the declarator, parse them.
1704    if (Tok.is(tok::kw___attribute)) {
1705      SourceLocation Loc;
1706      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1707      DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1708    }
1709
1710    // We're done with this declarator;  invoke the callback.
1711    DeclPtrTy D = Fields.invoke(DeclaratorInfo);
1712    PD.complete(D);
1713
1714    // If we don't have a comma, it is either the end of the list (a ';')
1715    // or an error, bail out.
1716    if (Tok.isNot(tok::comma))
1717      return;
1718
1719    // Consume the comma.
1720    ConsumeToken();
1721
1722    FirstDeclarator = false;
1723  }
1724}
1725
1726/// ParseStructUnionBody
1727///       struct-contents:
1728///         struct-declaration-list
1729/// [EXT]   empty
1730/// [GNU]   "struct-declaration-list" without terminatoring ';'
1731///       struct-declaration-list:
1732///         struct-declaration
1733///         struct-declaration-list struct-declaration
1734/// [OBC]   '@' 'defs' '(' class-name ')'
1735///
1736void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
1737                                  unsigned TagType, DeclPtrTy TagDecl) {
1738  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1739                                        PP.getSourceManager(),
1740                                        "parsing struct/union body");
1741
1742  SourceLocation LBraceLoc = ConsumeBrace();
1743
1744  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
1745  Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1746
1747  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
1748  // C++.
1749  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1750    Diag(Tok, diag::ext_empty_struct_union_enum)
1751      << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
1752
1753  llvm::SmallVector<DeclPtrTy, 32> FieldDecls;
1754
1755  // While we still have something to read, read the declarations in the struct.
1756  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1757    // Each iteration of this loop reads one struct-declaration.
1758
1759    // Check for extraneous top-level semicolon.
1760    if (Tok.is(tok::semi)) {
1761      Diag(Tok, diag::ext_extra_struct_semi)
1762        << FixItHint::CreateRemoval(Tok.getLocation());
1763      ConsumeToken();
1764      continue;
1765    }
1766
1767    // Parse all the comma separated declarators.
1768    DeclSpec DS;
1769
1770    if (!Tok.is(tok::at)) {
1771      struct CFieldCallback : FieldCallback {
1772        Parser &P;
1773        DeclPtrTy TagDecl;
1774        llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls;
1775
1776        CFieldCallback(Parser &P, DeclPtrTy TagDecl,
1777                       llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls) :
1778          P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
1779
1780        virtual DeclPtrTy invoke(FieldDeclarator &FD) {
1781          // Install the declarator into the current TagDecl.
1782          DeclPtrTy Field = P.Actions.ActOnField(P.CurScope, TagDecl,
1783                              FD.D.getDeclSpec().getSourceRange().getBegin(),
1784                                                 FD.D, FD.BitfieldSize);
1785          FieldDecls.push_back(Field);
1786          return Field;
1787        }
1788      } Callback(*this, TagDecl, FieldDecls);
1789
1790      ParseStructDeclaration(DS, Callback);
1791    } else { // Handle @defs
1792      ConsumeToken();
1793      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
1794        Diag(Tok, diag::err_unexpected_at);
1795        SkipUntil(tok::semi, true);
1796        continue;
1797      }
1798      ConsumeToken();
1799      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
1800      if (!Tok.is(tok::identifier)) {
1801        Diag(Tok, diag::err_expected_ident);
1802        SkipUntil(tok::semi, true);
1803        continue;
1804      }
1805      llvm::SmallVector<DeclPtrTy, 16> Fields;
1806      Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(),
1807                        Tok.getIdentifierInfo(), Fields);
1808      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
1809      ConsumeToken();
1810      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
1811    }
1812
1813    if (Tok.is(tok::semi)) {
1814      ConsumeToken();
1815    } else if (Tok.is(tok::r_brace)) {
1816      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
1817      break;
1818    } else {
1819      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
1820      // Skip to end of block or statement to avoid ext-warning on extra ';'.
1821      SkipUntil(tok::r_brace, true, true);
1822      // If we stopped at a ';', eat it.
1823      if (Tok.is(tok::semi)) ConsumeToken();
1824    }
1825  }
1826
1827  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1828
1829  llvm::OwningPtr<AttributeList> AttrList;
1830  // If attributes exist after struct contents, parse them.
1831  if (Tok.is(tok::kw___attribute))
1832    AttrList.reset(ParseGNUAttributes());
1833
1834  Actions.ActOnFields(CurScope,
1835                      RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
1836                      LBraceLoc, RBraceLoc,
1837                      AttrList.get());
1838  StructScope.Exit();
1839  Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1840}
1841
1842
1843/// ParseEnumSpecifier
1844///       enum-specifier: [C99 6.7.2.2]
1845///         'enum' identifier[opt] '{' enumerator-list '}'
1846///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1847/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1848///                                                 '}' attributes[opt]
1849///         'enum' identifier
1850/// [GNU]   'enum' attributes[opt] identifier
1851///
1852/// [C++] elaborated-type-specifier:
1853/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
1854///
1855void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
1856                                const ParsedTemplateInfo &TemplateInfo,
1857                                AccessSpecifier AS) {
1858  // Parse the tag portion of this.
1859  if (Tok.is(tok::code_completion)) {
1860    // Code completion for an enum name.
1861    Actions.CodeCompleteTag(CurScope, DeclSpec::TST_enum);
1862    ConsumeToken();
1863  }
1864
1865  llvm::OwningPtr<AttributeList> Attr;
1866  // If attributes exist after tag, parse them.
1867  if (Tok.is(tok::kw___attribute))
1868    Attr.reset(ParseGNUAttributes());
1869
1870  CXXScopeSpec SS;
1871  if (getLang().CPlusPlus) {
1872    if (ParseOptionalCXXScopeSpecifier(SS, 0, false))
1873      return;
1874
1875    if (SS.isSet() && Tok.isNot(tok::identifier)) {
1876      Diag(Tok, diag::err_expected_ident);
1877      if (Tok.isNot(tok::l_brace)) {
1878        // Has no name and is not a definition.
1879        // Skip the rest of this declarator, up until the comma or semicolon.
1880        SkipUntil(tok::comma, true);
1881        return;
1882      }
1883    }
1884  }
1885
1886  // Must have either 'enum name' or 'enum {...}'.
1887  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1888    Diag(Tok, diag::err_expected_ident_lbrace);
1889
1890    // Skip the rest of this declarator, up until the comma or semicolon.
1891    SkipUntil(tok::comma, true);
1892    return;
1893  }
1894
1895  // enums cannot be templates.
1896  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1897    Diag(Tok, diag::err_enum_template);
1898
1899    // Skip the rest of this declarator, up until the comma or semicolon.
1900    SkipUntil(tok::comma, true);
1901    return;
1902  }
1903
1904  // If an identifier is present, consume and remember it.
1905  IdentifierInfo *Name = 0;
1906  SourceLocation NameLoc;
1907  if (Tok.is(tok::identifier)) {
1908    Name = Tok.getIdentifierInfo();
1909    NameLoc = ConsumeToken();
1910  }
1911
1912  // There are three options here.  If we have 'enum foo;', then this is a
1913  // forward declaration.  If we have 'enum foo {...' then this is a
1914  // definition. Otherwise we have something like 'enum foo xyz', a reference.
1915  //
1916  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1917  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
1918  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
1919  //
1920  Action::TagUseKind TUK;
1921  if (Tok.is(tok::l_brace))
1922    TUK = Action::TUK_Definition;
1923  else if (Tok.is(tok::semi))
1924    TUK = Action::TUK_Declaration;
1925  else
1926    TUK = Action::TUK_Reference;
1927  bool Owned = false;
1928  bool IsDependent = false;
1929  DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TUK,
1930                                       StartLoc, SS, Name, NameLoc, Attr.get(),
1931                                       AS,
1932                                       Action::MultiTemplateParamsArg(Actions),
1933                                       Owned, IsDependent);
1934  assert(!IsDependent && "didn't expect dependent enum");
1935
1936  if (Tok.is(tok::l_brace))
1937    ParseEnumBody(StartLoc, TagDecl);
1938
1939  // FIXME: The DeclSpec should keep the locations of both the keyword and the
1940  // name (if there is one).
1941  SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc;
1942  const char *PrevSpec = 0;
1943  unsigned DiagID;
1944  if (DS.SetTypeSpecType(DeclSpec::TST_enum, TSTLoc, PrevSpec, DiagID,
1945                         TagDecl.getAs<void>(), Owned))
1946    Diag(StartLoc, DiagID) << PrevSpec;
1947}
1948
1949/// ParseEnumBody - Parse a {} enclosed enumerator-list.
1950///       enumerator-list:
1951///         enumerator
1952///         enumerator-list ',' enumerator
1953///       enumerator:
1954///         enumeration-constant
1955///         enumeration-constant '=' constant-expression
1956///       enumeration-constant:
1957///         identifier
1958///
1959void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) {
1960  // Enter the scope of the enum body and start the definition.
1961  ParseScope EnumScope(this, Scope::DeclScope);
1962  Actions.ActOnTagStartDefinition(CurScope, EnumDecl);
1963
1964  SourceLocation LBraceLoc = ConsumeBrace();
1965
1966  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
1967  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1968    Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
1969
1970  llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls;
1971
1972  DeclPtrTy LastEnumConstDecl;
1973
1974  // Parse the enumerator-list.
1975  while (Tok.is(tok::identifier)) {
1976    IdentifierInfo *Ident = Tok.getIdentifierInfo();
1977    SourceLocation IdentLoc = ConsumeToken();
1978
1979    SourceLocation EqualLoc;
1980    OwningExprResult AssignedVal(Actions);
1981    if (Tok.is(tok::equal)) {
1982      EqualLoc = ConsumeToken();
1983      AssignedVal = ParseConstantExpression();
1984      if (AssignedVal.isInvalid())
1985        SkipUntil(tok::comma, tok::r_brace, true, true);
1986    }
1987
1988    // Install the enumerator constant into EnumDecl.
1989    DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1990                                                        LastEnumConstDecl,
1991                                                        IdentLoc, Ident,
1992                                                        EqualLoc,
1993                                                        AssignedVal.release());
1994    EnumConstantDecls.push_back(EnumConstDecl);
1995    LastEnumConstDecl = EnumConstDecl;
1996
1997    if (Tok.isNot(tok::comma))
1998      break;
1999    SourceLocation CommaLoc = ConsumeToken();
2000
2001    if (Tok.isNot(tok::identifier) &&
2002        !(getLang().C99 || getLang().CPlusPlus0x))
2003      Diag(CommaLoc, diag::ext_enumerator_list_comma)
2004        << getLang().CPlusPlus
2005        << FixItHint::CreateRemoval(CommaLoc);
2006  }
2007
2008  // Eat the }.
2009  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2010
2011  llvm::OwningPtr<AttributeList> Attr;
2012  // If attributes exist after the identifier list, parse them.
2013  if (Tok.is(tok::kw___attribute))
2014    Attr.reset(ParseGNUAttributes()); // FIXME: where do they do?
2015
2016  Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
2017                        EnumConstantDecls.data(), EnumConstantDecls.size(),
2018                        CurScope, Attr.get());
2019
2020  EnumScope.Exit();
2021  Actions.ActOnTagFinishDefinition(CurScope, EnumDecl, RBraceLoc);
2022}
2023
2024/// isTypeSpecifierQualifier - Return true if the current token could be the
2025/// start of a type-qualifier-list.
2026bool Parser::isTypeQualifier() const {
2027  switch (Tok.getKind()) {
2028  default: return false;
2029    // type-qualifier
2030  case tok::kw_const:
2031  case tok::kw_volatile:
2032  case tok::kw_restrict:
2033    return true;
2034  }
2035}
2036
2037/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2038/// is definitely a type-specifier.  Return false if it isn't part of a type
2039/// specifier or if we're not sure.
2040bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
2041  switch (Tok.getKind()) {
2042  default: return false;
2043    // type-specifiers
2044  case tok::kw_short:
2045  case tok::kw_long:
2046  case tok::kw_signed:
2047  case tok::kw_unsigned:
2048  case tok::kw__Complex:
2049  case tok::kw__Imaginary:
2050  case tok::kw_void:
2051  case tok::kw_char:
2052  case tok::kw_wchar_t:
2053  case tok::kw_char16_t:
2054  case tok::kw_char32_t:
2055  case tok::kw_int:
2056  case tok::kw_float:
2057  case tok::kw_double:
2058  case tok::kw_bool:
2059  case tok::kw__Bool:
2060  case tok::kw__Decimal32:
2061  case tok::kw__Decimal64:
2062  case tok::kw__Decimal128:
2063  case tok::kw___vector:
2064
2065    // struct-or-union-specifier (C99) or class-specifier (C++)
2066  case tok::kw_class:
2067  case tok::kw_struct:
2068  case tok::kw_union:
2069    // enum-specifier
2070  case tok::kw_enum:
2071
2072    // typedef-name
2073  case tok::annot_typename:
2074    return true;
2075  }
2076}
2077
2078/// isTypeSpecifierQualifier - Return true if the current token could be the
2079/// start of a specifier-qualifier-list.
2080bool Parser::isTypeSpecifierQualifier() {
2081  switch (Tok.getKind()) {
2082  default: return false;
2083
2084  case tok::identifier:   // foo::bar
2085    if (TryAltiVecVectorToken())
2086      return true;
2087    // Fall through.
2088  case tok::kw_typename:  // typename T::type
2089    // Annotate typenames and C++ scope specifiers.  If we get one, just
2090    // recurse to handle whatever we get.
2091    if (TryAnnotateTypeOrScopeToken())
2092      return true;
2093    if (Tok.is(tok::identifier))
2094      return false;
2095    return isTypeSpecifierQualifier();
2096
2097  case tok::coloncolon:   // ::foo::bar
2098    if (NextToken().is(tok::kw_new) ||    // ::new
2099        NextToken().is(tok::kw_delete))   // ::delete
2100      return false;
2101
2102    if (TryAnnotateTypeOrScopeToken())
2103      return true;
2104    return isTypeSpecifierQualifier();
2105
2106    // GNU attributes support.
2107  case tok::kw___attribute:
2108    // GNU typeof support.
2109  case tok::kw_typeof:
2110
2111    // type-specifiers
2112  case tok::kw_short:
2113  case tok::kw_long:
2114  case tok::kw_signed:
2115  case tok::kw_unsigned:
2116  case tok::kw__Complex:
2117  case tok::kw__Imaginary:
2118  case tok::kw_void:
2119  case tok::kw_char:
2120  case tok::kw_wchar_t:
2121  case tok::kw_char16_t:
2122  case tok::kw_char32_t:
2123  case tok::kw_int:
2124  case tok::kw_float:
2125  case tok::kw_double:
2126  case tok::kw_bool:
2127  case tok::kw__Bool:
2128  case tok::kw__Decimal32:
2129  case tok::kw__Decimal64:
2130  case tok::kw__Decimal128:
2131  case tok::kw___vector:
2132
2133    // struct-or-union-specifier (C99) or class-specifier (C++)
2134  case tok::kw_class:
2135  case tok::kw_struct:
2136  case tok::kw_union:
2137    // enum-specifier
2138  case tok::kw_enum:
2139
2140    // type-qualifier
2141  case tok::kw_const:
2142  case tok::kw_volatile:
2143  case tok::kw_restrict:
2144
2145    // typedef-name
2146  case tok::annot_typename:
2147    return true;
2148
2149    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2150  case tok::less:
2151    return getLang().ObjC1;
2152
2153  case tok::kw___cdecl:
2154  case tok::kw___stdcall:
2155  case tok::kw___fastcall:
2156  case tok::kw___w64:
2157  case tok::kw___ptr64:
2158    return true;
2159  }
2160}
2161
2162/// isDeclarationSpecifier() - Return true if the current token is part of a
2163/// declaration specifier.
2164bool Parser::isDeclarationSpecifier() {
2165  switch (Tok.getKind()) {
2166  default: return false;
2167
2168  case tok::identifier:   // foo::bar
2169    // Unfortunate hack to support "Class.factoryMethod" notation.
2170    if (getLang().ObjC1 && NextToken().is(tok::period))
2171      return false;
2172    if (TryAltiVecVectorToken())
2173      return true;
2174    // Fall through.
2175  case tok::kw_typename: // typename T::type
2176    // Annotate typenames and C++ scope specifiers.  If we get one, just
2177    // recurse to handle whatever we get.
2178    if (TryAnnotateTypeOrScopeToken())
2179      return true;
2180    if (Tok.is(tok::identifier))
2181      return false;
2182    return isDeclarationSpecifier();
2183
2184  case tok::coloncolon:   // ::foo::bar
2185    if (NextToken().is(tok::kw_new) ||    // ::new
2186        NextToken().is(tok::kw_delete))   // ::delete
2187      return false;
2188
2189    // Annotate typenames and C++ scope specifiers.  If we get one, just
2190    // recurse to handle whatever we get.
2191    if (TryAnnotateTypeOrScopeToken())
2192      return true;
2193    return isDeclarationSpecifier();
2194
2195    // storage-class-specifier
2196  case tok::kw_typedef:
2197  case tok::kw_extern:
2198  case tok::kw___private_extern__:
2199  case tok::kw_static:
2200  case tok::kw_auto:
2201  case tok::kw_register:
2202  case tok::kw___thread:
2203
2204    // type-specifiers
2205  case tok::kw_short:
2206  case tok::kw_long:
2207  case tok::kw_signed:
2208  case tok::kw_unsigned:
2209  case tok::kw__Complex:
2210  case tok::kw__Imaginary:
2211  case tok::kw_void:
2212  case tok::kw_char:
2213  case tok::kw_wchar_t:
2214  case tok::kw_char16_t:
2215  case tok::kw_char32_t:
2216
2217  case tok::kw_int:
2218  case tok::kw_float:
2219  case tok::kw_double:
2220  case tok::kw_bool:
2221  case tok::kw__Bool:
2222  case tok::kw__Decimal32:
2223  case tok::kw__Decimal64:
2224  case tok::kw__Decimal128:
2225  case tok::kw___vector:
2226
2227    // struct-or-union-specifier (C99) or class-specifier (C++)
2228  case tok::kw_class:
2229  case tok::kw_struct:
2230  case tok::kw_union:
2231    // enum-specifier
2232  case tok::kw_enum:
2233
2234    // type-qualifier
2235  case tok::kw_const:
2236  case tok::kw_volatile:
2237  case tok::kw_restrict:
2238
2239    // function-specifier
2240  case tok::kw_inline:
2241  case tok::kw_virtual:
2242  case tok::kw_explicit:
2243
2244    // typedef-name
2245  case tok::annot_typename:
2246
2247    // GNU typeof support.
2248  case tok::kw_typeof:
2249
2250    // GNU attributes.
2251  case tok::kw___attribute:
2252    return true;
2253
2254    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2255  case tok::less:
2256    return getLang().ObjC1;
2257
2258  case tok::kw___declspec:
2259  case tok::kw___cdecl:
2260  case tok::kw___stdcall:
2261  case tok::kw___fastcall:
2262  case tok::kw___w64:
2263  case tok::kw___ptr64:
2264  case tok::kw___forceinline:
2265    return true;
2266  }
2267}
2268
2269bool Parser::isConstructorDeclarator() {
2270  TentativeParsingAction TPA(*this);
2271
2272  // Parse the C++ scope specifier.
2273  CXXScopeSpec SS;
2274  if (ParseOptionalCXXScopeSpecifier(SS, 0, true)) {
2275    TPA.Revert();
2276    return false;
2277  }
2278
2279  // Parse the constructor name.
2280  if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
2281    // We already know that we have a constructor name; just consume
2282    // the token.
2283    ConsumeToken();
2284  } else {
2285    TPA.Revert();
2286    return false;
2287  }
2288
2289  // Current class name must be followed by a left parentheses.
2290  if (Tok.isNot(tok::l_paren)) {
2291    TPA.Revert();
2292    return false;
2293  }
2294  ConsumeParen();
2295
2296  // A right parentheses or ellipsis signals that we have a constructor.
2297  if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
2298    TPA.Revert();
2299    return true;
2300  }
2301
2302  // If we need to, enter the specified scope.
2303  DeclaratorScopeObj DeclScopeObj(*this, SS);
2304  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(CurScope, SS))
2305    DeclScopeObj.EnterDeclaratorScope();
2306
2307  // Check whether the next token(s) are part of a declaration
2308  // specifier, in which case we have the start of a parameter and,
2309  // therefore, we know that this is a constructor.
2310  bool IsConstructor = isDeclarationSpecifier();
2311  TPA.Revert();
2312  return IsConstructor;
2313}
2314
2315/// ParseTypeQualifierListOpt
2316///       type-qualifier-list: [C99 6.7.5]
2317///         type-qualifier
2318/// [GNU]   attributes                        [ only if AttributesAllowed=true ]
2319///         type-qualifier-list type-qualifier
2320/// [GNU]   type-qualifier-list attributes    [ only if AttributesAllowed=true ]
2321/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
2322///           if CXX0XAttributesAllowed = true
2323///
2324void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed,
2325                                       bool CXX0XAttributesAllowed) {
2326  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
2327    SourceLocation Loc = Tok.getLocation();
2328    CXX0XAttributeList Attr = ParseCXX0XAttributes();
2329    if (CXX0XAttributesAllowed)
2330      DS.AddAttributes(Attr.AttrList);
2331    else
2332      Diag(Loc, diag::err_attributes_not_allowed);
2333  }
2334
2335  while (1) {
2336    bool isInvalid = false;
2337    const char *PrevSpec = 0;
2338    unsigned DiagID = 0;
2339    SourceLocation Loc = Tok.getLocation();
2340
2341    switch (Tok.getKind()) {
2342    case tok::kw_const:
2343      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
2344                                 getLang());
2345      break;
2346    case tok::kw_volatile:
2347      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
2348                                 getLang());
2349      break;
2350    case tok::kw_restrict:
2351      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
2352                                 getLang());
2353      break;
2354    case tok::kw___w64:
2355    case tok::kw___ptr64:
2356    case tok::kw___cdecl:
2357    case tok::kw___stdcall:
2358    case tok::kw___fastcall:
2359      if (GNUAttributesAllowed) {
2360        DS.AddAttributes(ParseMicrosoftTypeAttributes());
2361        continue;
2362      }
2363      goto DoneWithTypeQuals;
2364    case tok::kw___attribute:
2365      if (GNUAttributesAllowed) {
2366        DS.AddAttributes(ParseGNUAttributes());
2367        continue; // do *not* consume the next token!
2368      }
2369      // otherwise, FALL THROUGH!
2370    default:
2371      DoneWithTypeQuals:
2372      // If this is not a type-qualifier token, we're done reading type
2373      // qualifiers.  First verify that DeclSpec's are consistent.
2374      DS.Finish(Diags, PP);
2375      return;
2376    }
2377
2378    // If the specifier combination wasn't legal, issue a diagnostic.
2379    if (isInvalid) {
2380      assert(PrevSpec && "Method did not return previous specifier!");
2381      Diag(Tok, DiagID) << PrevSpec;
2382    }
2383    ConsumeToken();
2384  }
2385}
2386
2387
2388/// ParseDeclarator - Parse and verify a newly-initialized declarator.
2389///
2390void Parser::ParseDeclarator(Declarator &D) {
2391  /// This implements the 'declarator' production in the C grammar, then checks
2392  /// for well-formedness and issues diagnostics.
2393  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2394}
2395
2396/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
2397/// is parsed by the function passed to it. Pass null, and the direct-declarator
2398/// isn't parsed at all, making this function effectively parse the C++
2399/// ptr-operator production.
2400///
2401///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
2402/// [C]     pointer[opt] direct-declarator
2403/// [C++]   direct-declarator
2404/// [C++]   ptr-operator declarator
2405///
2406///       pointer: [C99 6.7.5]
2407///         '*' type-qualifier-list[opt]
2408///         '*' type-qualifier-list[opt] pointer
2409///
2410///       ptr-operator:
2411///         '*' cv-qualifier-seq[opt]
2412///         '&'
2413/// [C++0x] '&&'
2414/// [GNU]   '&' restrict[opt] attributes[opt]
2415/// [GNU?]  '&&' restrict[opt] attributes[opt]
2416///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
2417void Parser::ParseDeclaratorInternal(Declarator &D,
2418                                     DirectDeclParseFunction DirectDeclParser) {
2419  if (Diags.hasAllExtensionsSilenced())
2420    D.setExtension();
2421  // C++ member pointers start with a '::' or a nested-name.
2422  // Member pointers get special handling, since there's no place for the
2423  // scope spec in the generic path below.
2424  if (getLang().CPlusPlus &&
2425      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
2426       Tok.is(tok::annot_cxxscope))) {
2427    CXXScopeSpec SS;
2428    ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true); // ignore fail
2429
2430    if (SS.isNotEmpty()) {
2431      if (Tok.isNot(tok::star)) {
2432        // The scope spec really belongs to the direct-declarator.
2433        D.getCXXScopeSpec() = SS;
2434        if (DirectDeclParser)
2435          (this->*DirectDeclParser)(D);
2436        return;
2437      }
2438
2439      SourceLocation Loc = ConsumeToken();
2440      D.SetRangeEnd(Loc);
2441      DeclSpec DS;
2442      ParseTypeQualifierListOpt(DS);
2443      D.ExtendWithDeclSpec(DS);
2444
2445      // Recurse to parse whatever is left.
2446      ParseDeclaratorInternal(D, DirectDeclParser);
2447
2448      // Sema will have to catch (syntactically invalid) pointers into global
2449      // scope. It has to catch pointers into namespace scope anyway.
2450      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
2451                                                      Loc, DS.TakeAttributes()),
2452                    /* Don't replace range end. */SourceLocation());
2453      return;
2454    }
2455  }
2456
2457  tok::TokenKind Kind = Tok.getKind();
2458  // Not a pointer, C++ reference, or block.
2459  if (Kind != tok::star && Kind != tok::caret &&
2460      (Kind != tok::amp || !getLang().CPlusPlus) &&
2461      // We parse rvalue refs in C++03, because otherwise the errors are scary.
2462      (Kind != tok::ampamp || !getLang().CPlusPlus)) {
2463    if (DirectDeclParser)
2464      (this->*DirectDeclParser)(D);
2465    return;
2466  }
2467
2468  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
2469  // '&&' -> rvalue reference
2470  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
2471  D.SetRangeEnd(Loc);
2472
2473  if (Kind == tok::star || Kind == tok::caret) {
2474    // Is a pointer.
2475    DeclSpec DS;
2476
2477    ParseTypeQualifierListOpt(DS);
2478    D.ExtendWithDeclSpec(DS);
2479
2480    // Recursively parse the declarator.
2481    ParseDeclaratorInternal(D, DirectDeclParser);
2482    if (Kind == tok::star)
2483      // Remember that we parsed a pointer type, and remember the type-quals.
2484      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
2485                                                DS.TakeAttributes()),
2486                    SourceLocation());
2487    else
2488      // Remember that we parsed a Block type, and remember the type-quals.
2489      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
2490                                                     Loc, DS.TakeAttributes()),
2491                    SourceLocation());
2492  } else {
2493    // Is a reference
2494    DeclSpec DS;
2495
2496    // Complain about rvalue references in C++03, but then go on and build
2497    // the declarator.
2498    if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
2499      Diag(Loc, diag::err_rvalue_reference);
2500
2501    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
2502    // cv-qualifiers are introduced through the use of a typedef or of a
2503    // template type argument, in which case the cv-qualifiers are ignored.
2504    //
2505    // [GNU] Retricted references are allowed.
2506    // [GNU] Attributes on references are allowed.
2507    // [C++0x] Attributes on references are not allowed.
2508    ParseTypeQualifierListOpt(DS, true, false);
2509    D.ExtendWithDeclSpec(DS);
2510
2511    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2512      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2513        Diag(DS.getConstSpecLoc(),
2514             diag::err_invalid_reference_qualifier_application) << "const";
2515      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2516        Diag(DS.getVolatileSpecLoc(),
2517             diag::err_invalid_reference_qualifier_application) << "volatile";
2518    }
2519
2520    // Recursively parse the declarator.
2521    ParseDeclaratorInternal(D, DirectDeclParser);
2522
2523    if (D.getNumTypeObjects() > 0) {
2524      // C++ [dcl.ref]p4: There shall be no references to references.
2525      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
2526      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
2527        if (const IdentifierInfo *II = D.getIdentifier())
2528          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2529           << II;
2530        else
2531          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2532            << "type name";
2533
2534        // Once we've complained about the reference-to-reference, we
2535        // can go ahead and build the (technically ill-formed)
2536        // declarator: reference collapsing will take care of it.
2537      }
2538    }
2539
2540    // Remember that we parsed a reference type. It doesn't have type-quals.
2541    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
2542                                                DS.TakeAttributes(),
2543                                                Kind == tok::amp),
2544                  SourceLocation());
2545  }
2546}
2547
2548/// ParseDirectDeclarator
2549///       direct-declarator: [C99 6.7.5]
2550/// [C99]   identifier
2551///         '(' declarator ')'
2552/// [GNU]   '(' attributes declarator ')'
2553/// [C90]   direct-declarator '[' constant-expression[opt] ']'
2554/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2555/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2556/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2557/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
2558///         direct-declarator '(' parameter-type-list ')'
2559///         direct-declarator '(' identifier-list[opt] ')'
2560/// [GNU]   direct-declarator '(' parameter-forward-declarations
2561///                    parameter-type-list[opt] ')'
2562/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
2563///                    cv-qualifier-seq[opt] exception-specification[opt]
2564/// [C++]   declarator-id
2565///
2566///       declarator-id: [C++ 8]
2567///         id-expression
2568///         '::'[opt] nested-name-specifier[opt] type-name
2569///
2570///       id-expression: [C++ 5.1]
2571///         unqualified-id
2572///         qualified-id
2573///
2574///       unqualified-id: [C++ 5.1]
2575///         identifier
2576///         operator-function-id
2577///         conversion-function-id
2578///          '~' class-name
2579///         template-id
2580///
2581void Parser::ParseDirectDeclarator(Declarator &D) {
2582  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
2583
2584  if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
2585    // ParseDeclaratorInternal might already have parsed the scope.
2586    if (D.getCXXScopeSpec().isEmpty()) {
2587      ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), /*ObjectType=*/0,
2588                                     true);
2589    }
2590
2591    if (D.getCXXScopeSpec().isValid()) {
2592      if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec()))
2593        // Change the declaration context for name lookup, until this function
2594        // is exited (and the declarator has been parsed).
2595        DeclScopeObj.EnterDeclaratorScope();
2596    }
2597
2598    if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
2599        Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
2600      // We found something that indicates the start of an unqualified-id.
2601      // Parse that unqualified-id.
2602      bool AllowConstructorName
2603        = ((D.getCXXScopeSpec().isSet() &&
2604            D.getContext() == Declarator::FileContext) ||
2605           (!D.getCXXScopeSpec().isSet() &&
2606            D.getContext() == Declarator::MemberContext)) &&
2607        !D.getDeclSpec().hasTypeSpecifier();
2608      if (ParseUnqualifiedId(D.getCXXScopeSpec(),
2609                             /*EnteringContext=*/true,
2610                             /*AllowDestructorName=*/true,
2611                             AllowConstructorName,
2612                             /*ObjectType=*/0,
2613                             D.getName()) ||
2614          // Once we're past the identifier, if the scope was bad, mark the
2615          // whole declarator bad.
2616          D.getCXXScopeSpec().isInvalid()) {
2617        D.SetIdentifier(0, Tok.getLocation());
2618        D.setInvalidType(true);
2619      } else {
2620        // Parsed the unqualified-id; update range information and move along.
2621        if (D.getSourceRange().getBegin().isInvalid())
2622          D.SetRangeBegin(D.getName().getSourceRange().getBegin());
2623        D.SetRangeEnd(D.getName().getSourceRange().getEnd());
2624      }
2625      goto PastIdentifier;
2626    }
2627  } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
2628    assert(!getLang().CPlusPlus &&
2629           "There's a C++-specific check for tok::identifier above");
2630    assert(Tok.getIdentifierInfo() && "Not an identifier?");
2631    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2632    ConsumeToken();
2633    goto PastIdentifier;
2634  }
2635
2636  if (Tok.is(tok::l_paren)) {
2637    // direct-declarator: '(' declarator ')'
2638    // direct-declarator: '(' attributes declarator ')'
2639    // Example: 'char (*X)'   or 'int (*XX)(void)'
2640    ParseParenDeclarator(D);
2641
2642    // If the declarator was parenthesized, we entered the declarator
2643    // scope when parsing the parenthesized declarator, then exited
2644    // the scope already. Re-enter the scope, if we need to.
2645    if (D.getCXXScopeSpec().isSet()) {
2646      if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec()))
2647        // Change the declaration context for name lookup, until this function
2648        // is exited (and the declarator has been parsed).
2649        DeclScopeObj.EnterDeclaratorScope();
2650    }
2651  } else if (D.mayOmitIdentifier()) {
2652    // This could be something simple like "int" (in which case the declarator
2653    // portion is empty), if an abstract-declarator is allowed.
2654    D.SetIdentifier(0, Tok.getLocation());
2655  } else {
2656    if (D.getContext() == Declarator::MemberContext)
2657      Diag(Tok, diag::err_expected_member_name_or_semi)
2658        << D.getDeclSpec().getSourceRange();
2659    else if (getLang().CPlusPlus)
2660      Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
2661    else
2662      Diag(Tok, diag::err_expected_ident_lparen);
2663    D.SetIdentifier(0, Tok.getLocation());
2664    D.setInvalidType(true);
2665  }
2666
2667 PastIdentifier:
2668  assert(D.isPastIdentifier() &&
2669         "Haven't past the location of the identifier yet?");
2670
2671  // Don't parse attributes unless we have an identifier.
2672  if (D.getIdentifier() && getLang().CPlusPlus0x
2673   && isCXX0XAttributeSpecifier(true)) {
2674    SourceLocation AttrEndLoc;
2675    CXX0XAttributeList Attr = ParseCXX0XAttributes();
2676    D.AddAttributes(Attr.AttrList, AttrEndLoc);
2677  }
2678
2679  while (1) {
2680    if (Tok.is(tok::l_paren)) {
2681      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
2682      // In such a case, check if we actually have a function declarator; if it
2683      // is not, the declarator has been fully parsed.
2684      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
2685        // When not in file scope, warn for ambiguous function declarators, just
2686        // in case the author intended it as a variable definition.
2687        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
2688        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
2689          break;
2690      }
2691      ParseFunctionDeclarator(ConsumeParen(), D);
2692    } else if (Tok.is(tok::l_square)) {
2693      ParseBracketDeclarator(D);
2694    } else {
2695      break;
2696    }
2697  }
2698}
2699
2700/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
2701/// only called before the identifier, so these are most likely just grouping
2702/// parens for precedence.  If we find that these are actually function
2703/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
2704///
2705///       direct-declarator:
2706///         '(' declarator ')'
2707/// [GNU]   '(' attributes declarator ')'
2708///         direct-declarator '(' parameter-type-list ')'
2709///         direct-declarator '(' identifier-list[opt] ')'
2710/// [GNU]   direct-declarator '(' parameter-forward-declarations
2711///                    parameter-type-list[opt] ')'
2712///
2713void Parser::ParseParenDeclarator(Declarator &D) {
2714  SourceLocation StartLoc = ConsumeParen();
2715  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
2716
2717  // Eat any attributes before we look at whether this is a grouping or function
2718  // declarator paren.  If this is a grouping paren, the attribute applies to
2719  // the type being built up, for example:
2720  //     int (__attribute__(()) *x)(long y)
2721  // If this ends up not being a grouping paren, the attribute applies to the
2722  // first argument, for example:
2723  //     int (__attribute__(()) int x)
2724  // In either case, we need to eat any attributes to be able to determine what
2725  // sort of paren this is.
2726  //
2727  llvm::OwningPtr<AttributeList> AttrList;
2728  bool RequiresArg = false;
2729  if (Tok.is(tok::kw___attribute)) {
2730    AttrList.reset(ParseGNUAttributes());
2731
2732    // We require that the argument list (if this is a non-grouping paren) be
2733    // present even if the attribute list was empty.
2734    RequiresArg = true;
2735  }
2736  // Eat any Microsoft extensions.
2737  if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
2738       Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___w64) ||
2739       Tok.is(tok::kw___ptr64)) {
2740    AttrList.reset(ParseMicrosoftTypeAttributes(AttrList.take()));
2741  }
2742
2743  // If we haven't past the identifier yet (or where the identifier would be
2744  // stored, if this is an abstract declarator), then this is probably just
2745  // grouping parens. However, if this could be an abstract-declarator, then
2746  // this could also be the start of function arguments (consider 'void()').
2747  bool isGrouping;
2748
2749  if (!D.mayOmitIdentifier()) {
2750    // If this can't be an abstract-declarator, this *must* be a grouping
2751    // paren, because we haven't seen the identifier yet.
2752    isGrouping = true;
2753  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
2754             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
2755             isDeclarationSpecifier()) {       // 'int(int)' is a function.
2756    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
2757    // considered to be a type, not a K&R identifier-list.
2758    isGrouping = false;
2759  } else {
2760    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
2761    isGrouping = true;
2762  }
2763
2764  // If this is a grouping paren, handle:
2765  // direct-declarator: '(' declarator ')'
2766  // direct-declarator: '(' attributes declarator ')'
2767  if (isGrouping) {
2768    bool hadGroupingParens = D.hasGroupingParens();
2769    D.setGroupingParens(true);
2770    if (AttrList)
2771      D.AddAttributes(AttrList.take(), SourceLocation());
2772
2773    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2774    // Match the ')'.
2775    SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc);
2776
2777    D.setGroupingParens(hadGroupingParens);
2778    D.SetRangeEnd(Loc);
2779    return;
2780  }
2781
2782  // Okay, if this wasn't a grouping paren, it must be the start of a function
2783  // argument list.  Recognize that this declarator will never have an
2784  // identifier (and remember where it would have been), then call into
2785  // ParseFunctionDeclarator to handle of argument list.
2786  D.SetIdentifier(0, Tok.getLocation());
2787
2788  ParseFunctionDeclarator(StartLoc, D, AttrList.take(), RequiresArg);
2789}
2790
2791/// ParseFunctionDeclarator - We are after the identifier and have parsed the
2792/// declarator D up to a paren, which indicates that we are parsing function
2793/// arguments.
2794///
2795/// If AttrList is non-null, then the caller parsed those arguments immediately
2796/// after the open paren - they should be considered to be the first argument of
2797/// a parameter.  If RequiresArg is true, then the first argument of the
2798/// function is required to be present and required to not be an identifier
2799/// list.
2800///
2801/// This method also handles this portion of the grammar:
2802///       parameter-type-list: [C99 6.7.5]
2803///         parameter-list
2804///         parameter-list ',' '...'
2805/// [C++]   parameter-list '...'
2806///
2807///       parameter-list: [C99 6.7.5]
2808///         parameter-declaration
2809///         parameter-list ',' parameter-declaration
2810///
2811///       parameter-declaration: [C99 6.7.5]
2812///         declaration-specifiers declarator
2813/// [C++]   declaration-specifiers declarator '=' assignment-expression
2814/// [GNU]   declaration-specifiers declarator attributes
2815///         declaration-specifiers abstract-declarator[opt]
2816/// [C++]   declaration-specifiers abstract-declarator[opt]
2817///           '=' assignment-expression
2818/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
2819///
2820/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
2821/// and "exception-specification[opt]".
2822///
2823void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
2824                                     AttributeList *AttrList,
2825                                     bool RequiresArg) {
2826  // lparen is already consumed!
2827  assert(D.isPastIdentifier() && "Should not call before identifier!");
2828
2829  // This parameter list may be empty.
2830  if (Tok.is(tok::r_paren)) {
2831    if (RequiresArg) {
2832      Diag(Tok, diag::err_argument_required_after_attribute);
2833      delete AttrList;
2834    }
2835
2836    SourceLocation RParenLoc = ConsumeParen();  // Eat the closing ')'.
2837    SourceLocation EndLoc = RParenLoc;
2838
2839    // cv-qualifier-seq[opt].
2840    DeclSpec DS;
2841    bool hasExceptionSpec = false;
2842    SourceLocation ThrowLoc;
2843    bool hasAnyExceptionSpec = false;
2844    llvm::SmallVector<TypeTy*, 2> Exceptions;
2845    llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2846    if (getLang().CPlusPlus) {
2847      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2848      if (!DS.getSourceRange().getEnd().isInvalid())
2849        EndLoc = DS.getSourceRange().getEnd();
2850
2851      // Parse exception-specification[opt].
2852      if (Tok.is(tok::kw_throw)) {
2853        hasExceptionSpec = true;
2854        ThrowLoc = Tok.getLocation();
2855        ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
2856                                    hasAnyExceptionSpec);
2857        assert(Exceptions.size() == ExceptionRanges.size() &&
2858               "Produced different number of exception types and ranges.");
2859      }
2860    }
2861
2862    // Remember that we parsed a function type, and remember the attributes.
2863    // int() -> no prototype, no '...'.
2864    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
2865                                               /*variadic*/ false,
2866                                               SourceLocation(),
2867                                               /*arglist*/ 0, 0,
2868                                               DS.getTypeQualifiers(),
2869                                               hasExceptionSpec, ThrowLoc,
2870                                               hasAnyExceptionSpec,
2871                                               Exceptions.data(),
2872                                               ExceptionRanges.data(),
2873                                               Exceptions.size(),
2874                                               LParenLoc, RParenLoc, D),
2875                  EndLoc);
2876    return;
2877  }
2878
2879  // Alternatively, this parameter list may be an identifier list form for a
2880  // K&R-style function:  void foo(a,b,c)
2881  if (!getLang().CPlusPlus && Tok.is(tok::identifier)
2882      && !TryAltiVecVectorToken()) {
2883    if (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) {
2884      // K&R identifier lists can't have typedefs as identifiers, per
2885      // C99 6.7.5.3p11.
2886      if (RequiresArg) {
2887        Diag(Tok, diag::err_argument_required_after_attribute);
2888        delete AttrList;
2889      }
2890      // Identifier list.  Note that '(' identifier-list ')' is only allowed for
2891      // normal declarators, not for abstract-declarators.
2892      return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
2893    }
2894  }
2895
2896  // Finally, a normal, non-empty parameter type list.
2897
2898  // Build up an array of information about the parsed arguments.
2899  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2900
2901  // Enter function-declaration scope, limiting any declarators to the
2902  // function prototype scope, including parameter declarators.
2903  ParseScope PrototypeScope(this,
2904                            Scope::FunctionPrototypeScope|Scope::DeclScope);
2905
2906  bool IsVariadic = false;
2907  SourceLocation EllipsisLoc;
2908  while (1) {
2909    if (Tok.is(tok::ellipsis)) {
2910      IsVariadic = true;
2911      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
2912      break;
2913    }
2914
2915    SourceLocation DSStart = Tok.getLocation();
2916
2917    // Parse the declaration-specifiers.
2918    // Just use the ParsingDeclaration "scope" of the declarator.
2919    DeclSpec DS;
2920
2921    // If the caller parsed attributes for the first argument, add them now.
2922    if (AttrList) {
2923      DS.AddAttributes(AttrList);
2924      AttrList = 0;  // Only apply the attributes to the first parameter.
2925    }
2926    ParseDeclarationSpecifiers(DS);
2927
2928    // Parse the declarator.  This is "PrototypeContext", because we must
2929    // accept either 'declarator' or 'abstract-declarator' here.
2930    Declarator ParmDecl(DS, Declarator::PrototypeContext);
2931    ParseDeclarator(ParmDecl);
2932
2933    // Parse GNU attributes, if present.
2934    if (Tok.is(tok::kw___attribute)) {
2935      SourceLocation Loc;
2936      AttributeList *AttrList = ParseGNUAttributes(&Loc);
2937      ParmDecl.AddAttributes(AttrList, Loc);
2938    }
2939
2940    // Remember this parsed parameter in ParamInfo.
2941    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
2942
2943    // DefArgToks is used when the parsing of default arguments needs
2944    // to be delayed.
2945    CachedTokens *DefArgToks = 0;
2946
2947    // If no parameter was specified, verify that *something* was specified,
2948    // otherwise we have a missing type and identifier.
2949    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
2950        ParmDecl.getNumTypeObjects() == 0) {
2951      // Completely missing, emit error.
2952      Diag(DSStart, diag::err_missing_param);
2953    } else {
2954      // Otherwise, we have something.  Add it and let semantic analysis try
2955      // to grok it and add the result to the ParamInfo we are building.
2956
2957      // Inform the actions module about the parameter declarator, so it gets
2958      // added to the current scope.
2959      DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
2960
2961      // Parse the default argument, if any. We parse the default
2962      // arguments in all dialects; the semantic analysis in
2963      // ActOnParamDefaultArgument will reject the default argument in
2964      // C.
2965      if (Tok.is(tok::equal)) {
2966        SourceLocation EqualLoc = Tok.getLocation();
2967
2968        // Parse the default argument
2969        if (D.getContext() == Declarator::MemberContext) {
2970          // If we're inside a class definition, cache the tokens
2971          // corresponding to the default argument. We'll actually parse
2972          // them when we see the end of the class definition.
2973          // FIXME: Templates will require something similar.
2974          // FIXME: Can we use a smart pointer for Toks?
2975          DefArgToks = new CachedTokens;
2976
2977          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
2978                                    tok::semi, false)) {
2979            delete DefArgToks;
2980            DefArgToks = 0;
2981            Actions.ActOnParamDefaultArgumentError(Param);
2982          } else
2983            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
2984                                                (*DefArgToks)[1].getLocation());
2985        } else {
2986          // Consume the '='.
2987          ConsumeToken();
2988
2989          OwningExprResult DefArgResult(ParseAssignmentExpression());
2990          if (DefArgResult.isInvalid()) {
2991            Actions.ActOnParamDefaultArgumentError(Param);
2992            SkipUntil(tok::comma, tok::r_paren, true, true);
2993          } else {
2994            // Inform the actions module about the default argument
2995            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
2996                                              move(DefArgResult));
2997          }
2998        }
2999      }
3000
3001      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3002                                          ParmDecl.getIdentifierLoc(), Param,
3003                                          DefArgToks));
3004    }
3005
3006    // If the next token is a comma, consume it and keep reading arguments.
3007    if (Tok.isNot(tok::comma)) {
3008      if (Tok.is(tok::ellipsis)) {
3009        IsVariadic = true;
3010        EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
3011
3012        if (!getLang().CPlusPlus) {
3013          // We have ellipsis without a preceding ',', which is ill-formed
3014          // in C. Complain and provide the fix.
3015          Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
3016            << FixItHint::CreateInsertion(EllipsisLoc, ", ");
3017        }
3018      }
3019
3020      break;
3021    }
3022
3023    // Consume the comma.
3024    ConsumeToken();
3025  }
3026
3027  // Leave prototype scope.
3028  PrototypeScope.Exit();
3029
3030  // If we have the closing ')', eat it.
3031  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3032  SourceLocation EndLoc = RParenLoc;
3033
3034  DeclSpec DS;
3035  bool hasExceptionSpec = false;
3036  SourceLocation ThrowLoc;
3037  bool hasAnyExceptionSpec = false;
3038  llvm::SmallVector<TypeTy*, 2> Exceptions;
3039  llvm::SmallVector<SourceRange, 2> ExceptionRanges;
3040
3041  if (getLang().CPlusPlus) {
3042    // Parse cv-qualifier-seq[opt].
3043    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3044      if (!DS.getSourceRange().getEnd().isInvalid())
3045        EndLoc = DS.getSourceRange().getEnd();
3046
3047    // Parse exception-specification[opt].
3048    if (Tok.is(tok::kw_throw)) {
3049      hasExceptionSpec = true;
3050      ThrowLoc = Tok.getLocation();
3051      ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
3052                                  hasAnyExceptionSpec);
3053      assert(Exceptions.size() == ExceptionRanges.size() &&
3054             "Produced different number of exception types and ranges.");
3055    }
3056  }
3057
3058  // Remember that we parsed a function type, and remember the attributes.
3059  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
3060                                             EllipsisLoc,
3061                                             ParamInfo.data(), ParamInfo.size(),
3062                                             DS.getTypeQualifiers(),
3063                                             hasExceptionSpec, ThrowLoc,
3064                                             hasAnyExceptionSpec,
3065                                             Exceptions.data(),
3066                                             ExceptionRanges.data(),
3067                                             Exceptions.size(),
3068                                             LParenLoc, RParenLoc, D),
3069                EndLoc);
3070}
3071
3072/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
3073/// we found a K&R-style identifier list instead of a type argument list.  The
3074/// current token is known to be the first identifier in the list.
3075///
3076///       identifier-list: [C99 6.7.5]
3077///         identifier
3078///         identifier-list ',' identifier
3079///
3080void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
3081                                                   Declarator &D) {
3082  // Build up an array of information about the parsed arguments.
3083  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3084  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
3085
3086  // If there was no identifier specified for the declarator, either we are in
3087  // an abstract-declarator, or we are in a parameter declarator which was found
3088  // to be abstract.  In abstract-declarators, identifier lists are not valid:
3089  // diagnose this.
3090  if (!D.getIdentifier())
3091    Diag(Tok, diag::ext_ident_list_in_param);
3092
3093  // Tok is known to be the first identifier in the list.  Remember this
3094  // identifier in ParamInfo.
3095  ParamsSoFar.insert(Tok.getIdentifierInfo());
3096  ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
3097                                                 Tok.getLocation(),
3098                                                 DeclPtrTy()));
3099
3100  ConsumeToken();  // eat the first identifier.
3101
3102  while (Tok.is(tok::comma)) {
3103    // Eat the comma.
3104    ConsumeToken();
3105
3106    // If this isn't an identifier, report the error and skip until ')'.
3107    if (Tok.isNot(tok::identifier)) {
3108      Diag(Tok, diag::err_expected_ident);
3109      SkipUntil(tok::r_paren);
3110      return;
3111    }
3112
3113    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
3114
3115    // Reject 'typedef int y; int test(x, y)', but continue parsing.
3116    if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope))
3117      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
3118
3119    // Verify that the argument identifier has not already been mentioned.
3120    if (!ParamsSoFar.insert(ParmII)) {
3121      Diag(Tok, diag::err_param_redefinition) << ParmII;
3122    } else {
3123      // Remember this identifier in ParamInfo.
3124      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3125                                                     Tok.getLocation(),
3126                                                     DeclPtrTy()));
3127    }
3128
3129    // Eat the identifier.
3130    ConsumeToken();
3131  }
3132
3133  // If we have the closing ')', eat it and we're done.
3134  SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3135
3136  // Remember that we parsed a function type, and remember the attributes.  This
3137  // function type is always a K&R style function type, which is not varargs and
3138  // has no prototype.
3139  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
3140                                             SourceLocation(),
3141                                             &ParamInfo[0], ParamInfo.size(),
3142                                             /*TypeQuals*/0,
3143                                             /*exception*/false,
3144                                             SourceLocation(), false, 0, 0, 0,
3145                                             LParenLoc, RLoc, D),
3146                RLoc);
3147}
3148
3149/// [C90]   direct-declarator '[' constant-expression[opt] ']'
3150/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3151/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3152/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3153/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
3154void Parser::ParseBracketDeclarator(Declarator &D) {
3155  SourceLocation StartLoc = ConsumeBracket();
3156
3157  // C array syntax has many features, but by-far the most common is [] and [4].
3158  // This code does a fast path to handle some of the most obvious cases.
3159  if (Tok.getKind() == tok::r_square) {
3160    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3161    //FIXME: Use these
3162    CXX0XAttributeList Attr;
3163    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier(true)) {
3164      Attr = ParseCXX0XAttributes();
3165    }
3166
3167    // Remember that we parsed the empty array type.
3168    OwningExprResult NumElements(Actions);
3169    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
3170                                            StartLoc, EndLoc),
3171                  EndLoc);
3172    return;
3173  } else if (Tok.getKind() == tok::numeric_constant &&
3174             GetLookAheadToken(1).is(tok::r_square)) {
3175    // [4] is very common.  Parse the numeric constant expression.
3176    OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
3177    ConsumeToken();
3178
3179    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3180    //FIXME: Use these
3181    CXX0XAttributeList Attr;
3182    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3183      Attr = ParseCXX0XAttributes();
3184    }
3185
3186    // If there was an error parsing the assignment-expression, recover.
3187    if (ExprRes.isInvalid())
3188      ExprRes.release();  // Deallocate expr, just use [].
3189
3190    // Remember that we parsed a array type, and remember its features.
3191    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(),
3192                                            StartLoc, EndLoc),
3193                  EndLoc);
3194    return;
3195  }
3196
3197  // If valid, this location is the position where we read the 'static' keyword.
3198  SourceLocation StaticLoc;
3199  if (Tok.is(tok::kw_static))
3200    StaticLoc = ConsumeToken();
3201
3202  // If there is a type-qualifier-list, read it now.
3203  // Type qualifiers in an array subscript are a C99 feature.
3204  DeclSpec DS;
3205  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3206
3207  // If we haven't already read 'static', check to see if there is one after the
3208  // type-qualifier-list.
3209  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
3210    StaticLoc = ConsumeToken();
3211
3212  // Handle "direct-declarator [ type-qual-list[opt] * ]".
3213  bool isStar = false;
3214  OwningExprResult NumElements(Actions);
3215
3216  // Handle the case where we have '[*]' as the array size.  However, a leading
3217  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
3218  // the the token after the star is a ']'.  Since stars in arrays are
3219  // infrequent, use of lookahead is not costly here.
3220  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
3221    ConsumeToken();  // Eat the '*'.
3222
3223    if (StaticLoc.isValid()) {
3224      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
3225      StaticLoc = SourceLocation();  // Drop the static.
3226    }
3227    isStar = true;
3228  } else if (Tok.isNot(tok::r_square)) {
3229    // Note, in C89, this production uses the constant-expr production instead
3230    // of assignment-expr.  The only difference is that assignment-expr allows
3231    // things like '=' and '*='.  Sema rejects these in C89 mode because they
3232    // are not i-c-e's, so we don't need to distinguish between the two here.
3233
3234    // Parse the constant-expression or assignment-expression now (depending
3235    // on dialect).
3236    if (getLang().CPlusPlus)
3237      NumElements = ParseConstantExpression();
3238    else
3239      NumElements = ParseAssignmentExpression();
3240  }
3241
3242  // If there was an error parsing the assignment-expression, recover.
3243  if (NumElements.isInvalid()) {
3244    D.setInvalidType(true);
3245    // If the expression was invalid, skip it.
3246    SkipUntil(tok::r_square);
3247    return;
3248  }
3249
3250  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3251
3252  //FIXME: Use these
3253  CXX0XAttributeList Attr;
3254  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3255    Attr = ParseCXX0XAttributes();
3256  }
3257
3258  // Remember that we parsed a array type, and remember its features.
3259  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
3260                                          StaticLoc.isValid(), isStar,
3261                                          NumElements.release(),
3262                                          StartLoc, EndLoc),
3263                EndLoc);
3264}
3265
3266/// [GNU]   typeof-specifier:
3267///           typeof ( expressions )
3268///           typeof ( type-name )
3269/// [GNU/C++] typeof unary-expression
3270///
3271void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
3272  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
3273  Token OpTok = Tok;
3274  SourceLocation StartLoc = ConsumeToken();
3275
3276  const bool hasParens = Tok.is(tok::l_paren);
3277
3278  bool isCastExpr;
3279  TypeTy *CastTy;
3280  SourceRange CastRange;
3281  OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok,
3282                                                               isCastExpr,
3283                                                               CastTy,
3284                                                               CastRange);
3285  if (hasParens)
3286    DS.setTypeofParensRange(CastRange);
3287
3288  if (CastRange.getEnd().isInvalid())
3289    // FIXME: Not accurate, the range gets one token more than it should.
3290    DS.SetRangeEnd(Tok.getLocation());
3291  else
3292    DS.SetRangeEnd(CastRange.getEnd());
3293
3294  if (isCastExpr) {
3295    if (!CastTy) {
3296      DS.SetTypeSpecError();
3297      return;
3298    }
3299
3300    const char *PrevSpec = 0;
3301    unsigned DiagID;
3302    // Check for duplicate type specifiers (e.g. "int typeof(int)").
3303    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
3304                           DiagID, CastTy))
3305      Diag(StartLoc, DiagID) << PrevSpec;
3306    return;
3307  }
3308
3309  // If we get here, the operand to the typeof was an expresion.
3310  if (Operand.isInvalid()) {
3311    DS.SetTypeSpecError();
3312    return;
3313  }
3314
3315  const char *PrevSpec = 0;
3316  unsigned DiagID;
3317  // Check for duplicate type specifiers (e.g. "int typeof(int)").
3318  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
3319                         DiagID, Operand.release()))
3320    Diag(StartLoc, DiagID) << PrevSpec;
3321}
3322
3323
3324/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
3325/// from TryAltiVecVectorToken.
3326bool Parser::TryAltiVecVectorTokenOutOfLine() {
3327  Token Next = NextToken();
3328  switch (Next.getKind()) {
3329  default: return false;
3330  case tok::kw_short:
3331  case tok::kw_long:
3332  case tok::kw_signed:
3333  case tok::kw_unsigned:
3334  case tok::kw_void:
3335  case tok::kw_char:
3336  case tok::kw_int:
3337  case tok::kw_float:
3338  case tok::kw_double:
3339  case tok::kw_bool:
3340  case tok::kw___pixel:
3341    Tok.setKind(tok::kw___vector);
3342    return true;
3343  case tok::identifier:
3344    if (Next.getIdentifierInfo() == Ident_pixel) {
3345      Tok.setKind(tok::kw___vector);
3346      return true;
3347    }
3348    return false;
3349  }
3350}
3351
3352bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
3353                                      const char *&PrevSpec, unsigned &DiagID,
3354                                      bool &isInvalid) {
3355  if (Tok.getIdentifierInfo() == Ident_vector) {
3356    Token Next = NextToken();
3357    switch (Next.getKind()) {
3358    case tok::kw_short:
3359    case tok::kw_long:
3360    case tok::kw_signed:
3361    case tok::kw_unsigned:
3362    case tok::kw_void:
3363    case tok::kw_char:
3364    case tok::kw_int:
3365    case tok::kw_float:
3366    case tok::kw_double:
3367    case tok::kw_bool:
3368    case tok::kw___pixel:
3369      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
3370      return true;
3371    case tok::identifier:
3372      if (Next.getIdentifierInfo() == Ident_pixel) {
3373        isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
3374        return true;
3375      }
3376      break;
3377    default:
3378      break;
3379    }
3380  } else if (Tok.getIdentifierInfo() == Ident_pixel &&
3381             DS.isTypeAltiVecVector()) {
3382    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
3383    return true;
3384  }
3385  return false;
3386}
3387
3388