ParseDecl.cpp revision 14b91628961ab50cc6e724bbcd408fdee100662d
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 ||
908             (DSContext == DSC_class && DS.isFriendSpecified())) &&
909            TemplateId->Name &&
910            Actions.isCurrentClassName(*TemplateId->Name, CurScope, &SS)) {
911          if (isConstructorDeclarator()) {
912            // The user meant this to be an out-of-line constructor
913            // definition, but template arguments are not allowed
914            // there.  Just allow this as a constructor; we'll
915            // complain about it later.
916            goto DoneWithDeclSpec;
917          }
918
919          // The user meant this to name a type, but it actually names
920          // a constructor with some extraneous template
921          // arguments. Complain, then parse it as a type as the user
922          // intended.
923          Diag(TemplateId->TemplateNameLoc,
924               diag::err_out_of_line_template_id_names_constructor)
925            << TemplateId->Name;
926        }
927
928        DS.getTypeSpecScope() = SS;
929        ConsumeToken(); // The C++ scope.
930        assert(Tok.is(tok::annot_template_id) &&
931               "ParseOptionalCXXScopeSpecifier not working");
932        AnnotateTemplateIdTokenAsType(&SS);
933        continue;
934      }
935
936      if (Next.is(tok::annot_typename)) {
937        DS.getTypeSpecScope() = SS;
938        ConsumeToken(); // The C++ scope.
939        if (Tok.getAnnotationValue())
940          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc,
941                                         PrevSpec, DiagID,
942                                         Tok.getAnnotationValue());
943        else
944          DS.SetTypeSpecError();
945        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
946        ConsumeToken(); // The typename
947      }
948
949      if (Next.isNot(tok::identifier))
950        goto DoneWithDeclSpec;
951
952      // If we're in a context where the identifier could be a class name,
953      // check whether this is a constructor declaration.
954      if ((DSContext == DSC_top_level ||
955           (DSContext == DSC_class && DS.isFriendSpecified())) &&
956          Actions.isCurrentClassName(*Next.getIdentifierInfo(), CurScope,
957                                     &SS)) {
958        if (isConstructorDeclarator())
959          goto DoneWithDeclSpec;
960
961        // As noted in C++ [class.qual]p2 (cited above), when the name
962        // of the class is qualified in a context where it could name
963        // a constructor, its a constructor name. However, we've
964        // looked at the declarator, and the user probably meant this
965        // to be a type. Complain that it isn't supposed to be treated
966        // as a type, then proceed to parse it as a type.
967        Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
968          << Next.getIdentifierInfo();
969      }
970
971      TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
972                                            Next.getLocation(), CurScope, &SS);
973
974      // If the referenced identifier is not a type, then this declspec is
975      // erroneous: We already checked about that it has no type specifier, and
976      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
977      // typename.
978      if (TypeRep == 0) {
979        ConsumeToken();   // Eat the scope spec so the identifier is current.
980        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
981        goto DoneWithDeclSpec;
982      }
983
984      DS.getTypeSpecScope() = SS;
985      ConsumeToken(); // The C++ scope.
986
987      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
988                                     DiagID, TypeRep);
989      if (isInvalid)
990        break;
991
992      DS.SetRangeEnd(Tok.getLocation());
993      ConsumeToken(); // The typename.
994
995      continue;
996    }
997
998    case tok::annot_typename: {
999      if (Tok.getAnnotationValue())
1000        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1001                                       DiagID, Tok.getAnnotationValue());
1002      else
1003        DS.SetTypeSpecError();
1004
1005      if (isInvalid)
1006        break;
1007
1008      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1009      ConsumeToken(); // The typename
1010
1011      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1012      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1013      // Objective-C interface.  If we don't have Objective-C or a '<', this is
1014      // just a normal reference to a typedef name.
1015      if (!Tok.is(tok::less) || !getLang().ObjC1)
1016        continue;
1017
1018      SourceLocation LAngleLoc, EndProtoLoc;
1019      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1020      llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1021      ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1022                                  LAngleLoc, EndProtoLoc);
1023      DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1024                               ProtocolLocs.data(), LAngleLoc);
1025
1026      DS.SetRangeEnd(EndProtoLoc);
1027      continue;
1028    }
1029
1030      // typedef-name
1031    case tok::identifier: {
1032      // In C++, check to see if this is a scope specifier like foo::bar::, if
1033      // so handle it as such.  This is important for ctor parsing.
1034      if (getLang().CPlusPlus) {
1035        if (TryAnnotateCXXScopeToken(true)) {
1036          if (!DS.hasTypeSpecifier())
1037            DS.SetTypeSpecError();
1038          goto DoneWithDeclSpec;
1039        }
1040        if (!Tok.is(tok::identifier))
1041          continue;
1042      }
1043
1044      // This identifier can only be a typedef name if we haven't already seen
1045      // a type-specifier.  Without this check we misparse:
1046      //  typedef int X; struct Y { short X; };  as 'short int'.
1047      if (DS.hasTypeSpecifier())
1048        goto DoneWithDeclSpec;
1049
1050      // Check for need to substitute AltiVec keyword tokens.
1051      if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1052        break;
1053
1054      // It has to be available as a typedef too!
1055      TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(),
1056                                            Tok.getLocation(), CurScope);
1057
1058      // If this is not a typedef name, don't parse it as part of the declspec,
1059      // it must be an implicit int or an error.
1060      if (TypeRep == 0) {
1061        if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
1062        goto DoneWithDeclSpec;
1063      }
1064
1065      // If we're in a context where the identifier could be a class name,
1066      // check whether this is a constructor declaration.
1067      if (getLang().CPlusPlus && DSContext == DSC_class &&
1068          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
1069          isConstructorDeclarator())
1070        goto DoneWithDeclSpec;
1071
1072      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1073                                     DiagID, TypeRep);
1074      if (isInvalid)
1075        break;
1076
1077      DS.SetRangeEnd(Tok.getLocation());
1078      ConsumeToken(); // The identifier
1079
1080      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1081      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1082      // Objective-C interface.  If we don't have Objective-C or a '<', this is
1083      // just a normal reference to a typedef name.
1084      if (!Tok.is(tok::less) || !getLang().ObjC1)
1085        continue;
1086
1087      SourceLocation LAngleLoc, EndProtoLoc;
1088      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1089      llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1090      ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1091                                  LAngleLoc, EndProtoLoc);
1092      DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1093                               ProtocolLocs.data(), LAngleLoc);
1094
1095      DS.SetRangeEnd(EndProtoLoc);
1096
1097      // Need to support trailing type qualifiers (e.g. "id<p> const").
1098      // If a type specifier follows, it will be diagnosed elsewhere.
1099      continue;
1100    }
1101
1102      // type-name
1103    case tok::annot_template_id: {
1104      TemplateIdAnnotation *TemplateId
1105        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1106      if (TemplateId->Kind != TNK_Type_template) {
1107        // This template-id does not refer to a type name, so we're
1108        // done with the type-specifiers.
1109        goto DoneWithDeclSpec;
1110      }
1111
1112      // If we're in a context where the template-id could be a
1113      // constructor name or specialization, check whether this is a
1114      // constructor declaration.
1115      if (getLang().CPlusPlus && DSContext == DSC_class &&
1116          Actions.isCurrentClassName(*TemplateId->Name, CurScope) &&
1117          isConstructorDeclarator())
1118        goto DoneWithDeclSpec;
1119
1120      // Turn the template-id annotation token into a type annotation
1121      // token, then try again to parse it as a type-specifier.
1122      AnnotateTemplateIdTokenAsType();
1123      continue;
1124    }
1125
1126    // GNU attributes support.
1127    case tok::kw___attribute:
1128      DS.AddAttributes(ParseGNUAttributes());
1129      continue;
1130
1131    // Microsoft declspec support.
1132    case tok::kw___declspec:
1133      DS.AddAttributes(ParseMicrosoftDeclSpec());
1134      continue;
1135
1136    // Microsoft single token adornments.
1137    case tok::kw___forceinline:
1138      // FIXME: Add handling here!
1139      break;
1140
1141    case tok::kw___ptr64:
1142    case tok::kw___w64:
1143    case tok::kw___cdecl:
1144    case tok::kw___stdcall:
1145    case tok::kw___fastcall:
1146      DS.AddAttributes(ParseMicrosoftTypeAttributes());
1147      continue;
1148
1149    // storage-class-specifier
1150    case tok::kw_typedef:
1151      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
1152                                         DiagID);
1153      break;
1154    case tok::kw_extern:
1155      if (DS.isThreadSpecified())
1156        Diag(Tok, diag::ext_thread_before) << "extern";
1157      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1158                                         DiagID);
1159      break;
1160    case tok::kw___private_extern__:
1161      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1162                                         PrevSpec, DiagID);
1163      break;
1164    case tok::kw_static:
1165      if (DS.isThreadSpecified())
1166        Diag(Tok, diag::ext_thread_before) << "static";
1167      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1168                                         DiagID);
1169      break;
1170    case tok::kw_auto:
1171      if (getLang().CPlusPlus0x)
1172        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1173                                       DiagID);
1174      else
1175        isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1176                                           DiagID);
1177      break;
1178    case tok::kw_register:
1179      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1180                                         DiagID);
1181      break;
1182    case tok::kw_mutable:
1183      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1184                                         DiagID);
1185      break;
1186    case tok::kw___thread:
1187      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1188      break;
1189
1190    // function-specifier
1191    case tok::kw_inline:
1192      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1193      break;
1194    case tok::kw_virtual:
1195      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1196      break;
1197    case tok::kw_explicit:
1198      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1199      break;
1200
1201    // friend
1202    case tok::kw_friend:
1203      if (DSContext == DSC_class)
1204        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1205      else {
1206        PrevSpec = ""; // not actually used by the diagnostic
1207        DiagID = diag::err_friend_invalid_in_context;
1208        isInvalid = true;
1209      }
1210      break;
1211
1212    // constexpr
1213    case tok::kw_constexpr:
1214      isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
1215      break;
1216
1217    // type-specifier
1218    case tok::kw_short:
1219      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1220                                      DiagID);
1221      break;
1222    case tok::kw_long:
1223      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1224        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1225                                        DiagID);
1226      else
1227        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1228                                        DiagID);
1229      break;
1230    case tok::kw_signed:
1231      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1232                                     DiagID);
1233      break;
1234    case tok::kw_unsigned:
1235      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1236                                     DiagID);
1237      break;
1238    case tok::kw__Complex:
1239      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1240                                        DiagID);
1241      break;
1242    case tok::kw__Imaginary:
1243      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1244                                        DiagID);
1245      break;
1246    case tok::kw_void:
1247      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1248                                     DiagID);
1249      break;
1250    case tok::kw_char:
1251      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1252                                     DiagID);
1253      break;
1254    case tok::kw_int:
1255      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1256                                     DiagID);
1257      break;
1258    case tok::kw_float:
1259      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1260                                     DiagID);
1261      break;
1262    case tok::kw_double:
1263      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1264                                     DiagID);
1265      break;
1266    case tok::kw_wchar_t:
1267      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1268                                     DiagID);
1269      break;
1270    case tok::kw_char16_t:
1271      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1272                                     DiagID);
1273      break;
1274    case tok::kw_char32_t:
1275      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1276                                     DiagID);
1277      break;
1278    case tok::kw_bool:
1279    case tok::kw__Bool:
1280      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1281                                     DiagID);
1282      break;
1283    case tok::kw__Decimal32:
1284      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1285                                     DiagID);
1286      break;
1287    case tok::kw__Decimal64:
1288      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1289                                     DiagID);
1290      break;
1291    case tok::kw__Decimal128:
1292      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1293                                     DiagID);
1294      break;
1295    case tok::kw___vector:
1296      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1297      break;
1298    case tok::kw___pixel:
1299      isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1300      break;
1301
1302    // class-specifier:
1303    case tok::kw_class:
1304    case tok::kw_struct:
1305    case tok::kw_union: {
1306      tok::TokenKind Kind = Tok.getKind();
1307      ConsumeToken();
1308      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1309      continue;
1310    }
1311
1312    // enum-specifier:
1313    case tok::kw_enum:
1314      ConsumeToken();
1315      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1316      continue;
1317
1318    // cv-qualifier:
1319    case tok::kw_const:
1320      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1321                                 getLang());
1322      break;
1323    case tok::kw_volatile:
1324      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1325                                 getLang());
1326      break;
1327    case tok::kw_restrict:
1328      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1329                                 getLang());
1330      break;
1331
1332    // C++ typename-specifier:
1333    case tok::kw_typename:
1334      if (TryAnnotateTypeOrScopeToken()) {
1335        DS.SetTypeSpecError();
1336        goto DoneWithDeclSpec;
1337      }
1338      if (!Tok.is(tok::kw_typename))
1339        continue;
1340      break;
1341
1342    // GNU typeof support.
1343    case tok::kw_typeof:
1344      ParseTypeofSpecifier(DS);
1345      continue;
1346
1347    case tok::kw_decltype:
1348      ParseDecltypeSpecifier(DS);
1349      continue;
1350
1351    case tok::less:
1352      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1353      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
1354      // but we support it.
1355      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1356        goto DoneWithDeclSpec;
1357
1358      {
1359        SourceLocation LAngleLoc, EndProtoLoc;
1360        llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1361        llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1362        ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1363                                    LAngleLoc, EndProtoLoc);
1364        DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1365                                 ProtocolLocs.data(), LAngleLoc);
1366        DS.SetRangeEnd(EndProtoLoc);
1367
1368        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1369          << FixItHint::CreateInsertion(Loc, "id")
1370          << SourceRange(Loc, EndProtoLoc);
1371        // Need to support trailing type qualifiers (e.g. "id<p> const").
1372        // If a type specifier follows, it will be diagnosed elsewhere.
1373        continue;
1374      }
1375    }
1376    // If the specifier wasn't legal, issue a diagnostic.
1377    if (isInvalid) {
1378      assert(PrevSpec && "Method did not return previous specifier!");
1379      assert(DiagID);
1380      Diag(Tok, DiagID) << PrevSpec;
1381    }
1382    DS.SetRangeEnd(Tok.getLocation());
1383    ConsumeToken();
1384  }
1385}
1386
1387/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1388/// primarily follow the C++ grammar with additions for C99 and GNU,
1389/// which together subsume the C grammar. Note that the C++
1390/// type-specifier also includes the C type-qualifier (for const,
1391/// volatile, and C99 restrict). Returns true if a type-specifier was
1392/// found (and parsed), false otherwise.
1393///
1394///       type-specifier: [C++ 7.1.5]
1395///         simple-type-specifier
1396///         class-specifier
1397///         enum-specifier
1398///         elaborated-type-specifier  [TODO]
1399///         cv-qualifier
1400///
1401///       cv-qualifier: [C++ 7.1.5.1]
1402///         'const'
1403///         'volatile'
1404/// [C99]   'restrict'
1405///
1406///       simple-type-specifier: [ C++ 7.1.5.2]
1407///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
1408///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
1409///         'char'
1410///         'wchar_t'
1411///         'bool'
1412///         'short'
1413///         'int'
1414///         'long'
1415///         'signed'
1416///         'unsigned'
1417///         'float'
1418///         'double'
1419///         'void'
1420/// [C99]   '_Bool'
1421/// [C99]   '_Complex'
1422/// [C99]   '_Imaginary'  // Removed in TC2?
1423/// [GNU]   '_Decimal32'
1424/// [GNU]   '_Decimal64'
1425/// [GNU]   '_Decimal128'
1426/// [GNU]   typeof-specifier
1427/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
1428/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
1429/// [C++0x] 'decltype' ( expression )
1430/// [AltiVec] '__vector'
1431bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1432                                        const char *&PrevSpec,
1433                                        unsigned &DiagID,
1434                                        const ParsedTemplateInfo &TemplateInfo,
1435                                        bool SuppressDeclarations) {
1436  SourceLocation Loc = Tok.getLocation();
1437
1438  switch (Tok.getKind()) {
1439  case tok::identifier:   // foo::bar
1440    // If we already have a type specifier, this identifier is not a type.
1441    if (DS.getTypeSpecType() != DeclSpec::TST_unspecified ||
1442        DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
1443        DS.getTypeSpecSign() != DeclSpec::TSS_unspecified)
1444      return false;
1445    // Check for need to substitute AltiVec keyword tokens.
1446    if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1447      break;
1448    // Fall through.
1449  case tok::kw_typename:  // typename foo::bar
1450    // Annotate typenames and C++ scope specifiers.  If we get one, just
1451    // recurse to handle whatever we get.
1452    if (TryAnnotateTypeOrScopeToken())
1453      return true;
1454    if (Tok.is(tok::identifier))
1455      return false;
1456    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1457                                      TemplateInfo, SuppressDeclarations);
1458  case tok::coloncolon:   // ::foo::bar
1459    if (NextToken().is(tok::kw_new) ||    // ::new
1460        NextToken().is(tok::kw_delete))   // ::delete
1461      return false;
1462
1463    // Annotate typenames and C++ scope specifiers.  If we get one, just
1464    // recurse to handle whatever we get.
1465    if (TryAnnotateTypeOrScopeToken())
1466      return true;
1467    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1468                                      TemplateInfo, SuppressDeclarations);
1469
1470  // simple-type-specifier:
1471  case tok::annot_typename: {
1472    if (Tok.getAnnotationValue())
1473      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1474                                     DiagID, Tok.getAnnotationValue());
1475    else
1476      DS.SetTypeSpecError();
1477    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1478    ConsumeToken(); // The typename
1479
1480    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1481    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1482    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1483    // just a normal reference to a typedef name.
1484    if (!Tok.is(tok::less) || !getLang().ObjC1)
1485      return true;
1486
1487    SourceLocation LAngleLoc, EndProtoLoc;
1488    llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1489    llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1490    ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1491                                LAngleLoc, EndProtoLoc);
1492    DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1493                             ProtocolLocs.data(), LAngleLoc);
1494
1495    DS.SetRangeEnd(EndProtoLoc);
1496    return true;
1497  }
1498
1499  case tok::kw_short:
1500    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1501    break;
1502  case tok::kw_long:
1503    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1504      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1505                                      DiagID);
1506    else
1507      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1508                                      DiagID);
1509    break;
1510  case tok::kw_signed:
1511    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1512    break;
1513  case tok::kw_unsigned:
1514    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1515                                   DiagID);
1516    break;
1517  case tok::kw__Complex:
1518    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1519                                      DiagID);
1520    break;
1521  case tok::kw__Imaginary:
1522    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1523                                      DiagID);
1524    break;
1525  case tok::kw_void:
1526    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1527    break;
1528  case tok::kw_char:
1529    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1530    break;
1531  case tok::kw_int:
1532    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1533    break;
1534  case tok::kw_float:
1535    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1536    break;
1537  case tok::kw_double:
1538    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1539    break;
1540  case tok::kw_wchar_t:
1541    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1542    break;
1543  case tok::kw_char16_t:
1544    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1545    break;
1546  case tok::kw_char32_t:
1547    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1548    break;
1549  case tok::kw_bool:
1550  case tok::kw__Bool:
1551    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1552    break;
1553  case tok::kw__Decimal32:
1554    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1555                                   DiagID);
1556    break;
1557  case tok::kw__Decimal64:
1558    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1559                                   DiagID);
1560    break;
1561  case tok::kw__Decimal128:
1562    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1563                                   DiagID);
1564    break;
1565  case tok::kw___vector:
1566    isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1567    break;
1568  case tok::kw___pixel:
1569    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1570    break;
1571
1572  // class-specifier:
1573  case tok::kw_class:
1574  case tok::kw_struct:
1575  case tok::kw_union: {
1576    tok::TokenKind Kind = Tok.getKind();
1577    ConsumeToken();
1578    ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none,
1579                        SuppressDeclarations);
1580    return true;
1581  }
1582
1583  // enum-specifier:
1584  case tok::kw_enum:
1585    ConsumeToken();
1586    ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none);
1587    return true;
1588
1589  // cv-qualifier:
1590  case tok::kw_const:
1591    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1592                               DiagID, getLang());
1593    break;
1594  case tok::kw_volatile:
1595    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1596                               DiagID, getLang());
1597    break;
1598  case tok::kw_restrict:
1599    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1600                               DiagID, getLang());
1601    break;
1602
1603  // GNU typeof support.
1604  case tok::kw_typeof:
1605    ParseTypeofSpecifier(DS);
1606    return true;
1607
1608  // C++0x decltype support.
1609  case tok::kw_decltype:
1610    ParseDecltypeSpecifier(DS);
1611    return true;
1612
1613  // C++0x auto support.
1614  case tok::kw_auto:
1615    if (!getLang().CPlusPlus0x)
1616      return false;
1617
1618    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
1619    break;
1620  case tok::kw___ptr64:
1621  case tok::kw___w64:
1622  case tok::kw___cdecl:
1623  case tok::kw___stdcall:
1624  case tok::kw___fastcall:
1625    DS.AddAttributes(ParseMicrosoftTypeAttributes());
1626    return true;
1627
1628  default:
1629    // Not a type-specifier; do nothing.
1630    return false;
1631  }
1632
1633  // If the specifier combination wasn't legal, issue a diagnostic.
1634  if (isInvalid) {
1635    assert(PrevSpec && "Method did not return previous specifier!");
1636    // Pick between error or extwarn.
1637    Diag(Tok, DiagID) << PrevSpec;
1638  }
1639  DS.SetRangeEnd(Tok.getLocation());
1640  ConsumeToken(); // whatever we parsed above.
1641  return true;
1642}
1643
1644/// ParseStructDeclaration - Parse a struct declaration without the terminating
1645/// semicolon.
1646///
1647///       struct-declaration:
1648///         specifier-qualifier-list struct-declarator-list
1649/// [GNU]   __extension__ struct-declaration
1650/// [GNU]   specifier-qualifier-list
1651///       struct-declarator-list:
1652///         struct-declarator
1653///         struct-declarator-list ',' struct-declarator
1654/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
1655///       struct-declarator:
1656///         declarator
1657/// [GNU]   declarator attributes[opt]
1658///         declarator[opt] ':' constant-expression
1659/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
1660///
1661void Parser::
1662ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
1663  if (Tok.is(tok::kw___extension__)) {
1664    // __extension__ silences extension warnings in the subexpression.
1665    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1666    ConsumeToken();
1667    return ParseStructDeclaration(DS, Fields);
1668  }
1669
1670  // Parse the common specifier-qualifiers-list piece.
1671  SourceLocation DSStart = Tok.getLocation();
1672  ParseSpecifierQualifierList(DS);
1673
1674  // If there are no declarators, this is a free-standing declaration
1675  // specifier. Let the actions module cope with it.
1676  if (Tok.is(tok::semi)) {
1677    Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1678    return;
1679  }
1680
1681  // Read struct-declarators until we find the semicolon.
1682  bool FirstDeclarator = true;
1683  while (1) {
1684    ParsingDeclRAIIObject PD(*this);
1685    FieldDeclarator DeclaratorInfo(DS);
1686
1687    // Attributes are only allowed here on successive declarators.
1688    if (!FirstDeclarator && Tok.is(tok::kw___attribute)) {
1689      SourceLocation Loc;
1690      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1691      DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1692    }
1693
1694    /// struct-declarator: declarator
1695    /// struct-declarator: declarator[opt] ':' constant-expression
1696    if (Tok.isNot(tok::colon)) {
1697      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1698      ColonProtectionRAIIObject X(*this);
1699      ParseDeclarator(DeclaratorInfo.D);
1700    }
1701
1702    if (Tok.is(tok::colon)) {
1703      ConsumeToken();
1704      OwningExprResult Res(ParseConstantExpression());
1705      if (Res.isInvalid())
1706        SkipUntil(tok::semi, true, true);
1707      else
1708        DeclaratorInfo.BitfieldSize = Res.release();
1709    }
1710
1711    // If attributes exist after the declarator, parse them.
1712    if (Tok.is(tok::kw___attribute)) {
1713      SourceLocation Loc;
1714      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1715      DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1716    }
1717
1718    // We're done with this declarator;  invoke the callback.
1719    DeclPtrTy D = Fields.invoke(DeclaratorInfo);
1720    PD.complete(D);
1721
1722    // If we don't have a comma, it is either the end of the list (a ';')
1723    // or an error, bail out.
1724    if (Tok.isNot(tok::comma))
1725      return;
1726
1727    // Consume the comma.
1728    ConsumeToken();
1729
1730    FirstDeclarator = false;
1731  }
1732}
1733
1734/// ParseStructUnionBody
1735///       struct-contents:
1736///         struct-declaration-list
1737/// [EXT]   empty
1738/// [GNU]   "struct-declaration-list" without terminatoring ';'
1739///       struct-declaration-list:
1740///         struct-declaration
1741///         struct-declaration-list struct-declaration
1742/// [OBC]   '@' 'defs' '(' class-name ')'
1743///
1744void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
1745                                  unsigned TagType, DeclPtrTy TagDecl) {
1746  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1747                                        PP.getSourceManager(),
1748                                        "parsing struct/union body");
1749
1750  SourceLocation LBraceLoc = ConsumeBrace();
1751
1752  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
1753  Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1754
1755  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
1756  // C++.
1757  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1758    Diag(Tok, diag::ext_empty_struct_union_enum)
1759      << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
1760
1761  llvm::SmallVector<DeclPtrTy, 32> FieldDecls;
1762
1763  // While we still have something to read, read the declarations in the struct.
1764  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1765    // Each iteration of this loop reads one struct-declaration.
1766
1767    // Check for extraneous top-level semicolon.
1768    if (Tok.is(tok::semi)) {
1769      Diag(Tok, diag::ext_extra_struct_semi)
1770        << FixItHint::CreateRemoval(Tok.getLocation());
1771      ConsumeToken();
1772      continue;
1773    }
1774
1775    // Parse all the comma separated declarators.
1776    DeclSpec DS;
1777
1778    if (!Tok.is(tok::at)) {
1779      struct CFieldCallback : FieldCallback {
1780        Parser &P;
1781        DeclPtrTy TagDecl;
1782        llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls;
1783
1784        CFieldCallback(Parser &P, DeclPtrTy TagDecl,
1785                       llvm::SmallVectorImpl<DeclPtrTy> &FieldDecls) :
1786          P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
1787
1788        virtual DeclPtrTy invoke(FieldDeclarator &FD) {
1789          // Install the declarator into the current TagDecl.
1790          DeclPtrTy Field = P.Actions.ActOnField(P.CurScope, TagDecl,
1791                              FD.D.getDeclSpec().getSourceRange().getBegin(),
1792                                                 FD.D, FD.BitfieldSize);
1793          FieldDecls.push_back(Field);
1794          return Field;
1795        }
1796      } Callback(*this, TagDecl, FieldDecls);
1797
1798      ParseStructDeclaration(DS, Callback);
1799    } else { // Handle @defs
1800      ConsumeToken();
1801      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
1802        Diag(Tok, diag::err_unexpected_at);
1803        SkipUntil(tok::semi, true);
1804        continue;
1805      }
1806      ConsumeToken();
1807      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
1808      if (!Tok.is(tok::identifier)) {
1809        Diag(Tok, diag::err_expected_ident);
1810        SkipUntil(tok::semi, true);
1811        continue;
1812      }
1813      llvm::SmallVector<DeclPtrTy, 16> Fields;
1814      Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(),
1815                        Tok.getIdentifierInfo(), Fields);
1816      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
1817      ConsumeToken();
1818      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
1819    }
1820
1821    if (Tok.is(tok::semi)) {
1822      ConsumeToken();
1823    } else if (Tok.is(tok::r_brace)) {
1824      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
1825      break;
1826    } else {
1827      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
1828      // Skip to end of block or statement to avoid ext-warning on extra ';'.
1829      SkipUntil(tok::r_brace, true, true);
1830      // If we stopped at a ';', eat it.
1831      if (Tok.is(tok::semi)) ConsumeToken();
1832    }
1833  }
1834
1835  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1836
1837  llvm::OwningPtr<AttributeList> AttrList;
1838  // If attributes exist after struct contents, parse them.
1839  if (Tok.is(tok::kw___attribute))
1840    AttrList.reset(ParseGNUAttributes());
1841
1842  Actions.ActOnFields(CurScope,
1843                      RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
1844                      LBraceLoc, RBraceLoc,
1845                      AttrList.get());
1846  StructScope.Exit();
1847  Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1848}
1849
1850
1851/// ParseEnumSpecifier
1852///       enum-specifier: [C99 6.7.2.2]
1853///         'enum' identifier[opt] '{' enumerator-list '}'
1854///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1855/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1856///                                                 '}' attributes[opt]
1857///         'enum' identifier
1858/// [GNU]   'enum' attributes[opt] identifier
1859///
1860/// [C++] elaborated-type-specifier:
1861/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
1862///
1863void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
1864                                const ParsedTemplateInfo &TemplateInfo,
1865                                AccessSpecifier AS) {
1866  // Parse the tag portion of this.
1867  if (Tok.is(tok::code_completion)) {
1868    // Code completion for an enum name.
1869    Actions.CodeCompleteTag(CurScope, DeclSpec::TST_enum);
1870    ConsumeToken();
1871  }
1872
1873  llvm::OwningPtr<AttributeList> Attr;
1874  // If attributes exist after tag, parse them.
1875  if (Tok.is(tok::kw___attribute))
1876    Attr.reset(ParseGNUAttributes());
1877
1878  CXXScopeSpec SS;
1879  if (getLang().CPlusPlus) {
1880    if (ParseOptionalCXXScopeSpecifier(SS, 0, false))
1881      return;
1882
1883    if (SS.isSet() && Tok.isNot(tok::identifier)) {
1884      Diag(Tok, diag::err_expected_ident);
1885      if (Tok.isNot(tok::l_brace)) {
1886        // Has no name and is not a definition.
1887        // Skip the rest of this declarator, up until the comma or semicolon.
1888        SkipUntil(tok::comma, true);
1889        return;
1890      }
1891    }
1892  }
1893
1894  // Must have either 'enum name' or 'enum {...}'.
1895  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1896    Diag(Tok, diag::err_expected_ident_lbrace);
1897
1898    // Skip the rest of this declarator, up until the comma or semicolon.
1899    SkipUntil(tok::comma, true);
1900    return;
1901  }
1902
1903  // enums cannot be templates.
1904  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1905    Diag(Tok, diag::err_enum_template);
1906
1907    // Skip the rest of this declarator, up until the comma or semicolon.
1908    SkipUntil(tok::comma, true);
1909    return;
1910  }
1911
1912  // If an identifier is present, consume and remember it.
1913  IdentifierInfo *Name = 0;
1914  SourceLocation NameLoc;
1915  if (Tok.is(tok::identifier)) {
1916    Name = Tok.getIdentifierInfo();
1917    NameLoc = ConsumeToken();
1918  }
1919
1920  // There are three options here.  If we have 'enum foo;', then this is a
1921  // forward declaration.  If we have 'enum foo {...' then this is a
1922  // definition. Otherwise we have something like 'enum foo xyz', a reference.
1923  //
1924  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1925  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
1926  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
1927  //
1928  Action::TagUseKind TUK;
1929  if (Tok.is(tok::l_brace))
1930    TUK = Action::TUK_Definition;
1931  else if (Tok.is(tok::semi))
1932    TUK = Action::TUK_Declaration;
1933  else
1934    TUK = Action::TUK_Reference;
1935  bool Owned = false;
1936  bool IsDependent = false;
1937  DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TUK,
1938                                       StartLoc, SS, Name, NameLoc, Attr.get(),
1939                                       AS,
1940                                       Action::MultiTemplateParamsArg(Actions),
1941                                       Owned, IsDependent);
1942  assert(!IsDependent && "didn't expect dependent enum");
1943
1944  if (Tok.is(tok::l_brace))
1945    ParseEnumBody(StartLoc, TagDecl);
1946
1947  // FIXME: The DeclSpec should keep the locations of both the keyword and the
1948  // name (if there is one).
1949  SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc;
1950  const char *PrevSpec = 0;
1951  unsigned DiagID;
1952  if (DS.SetTypeSpecType(DeclSpec::TST_enum, TSTLoc, PrevSpec, DiagID,
1953                         TagDecl.getAs<void>(), Owned))
1954    Diag(StartLoc, DiagID) << PrevSpec;
1955}
1956
1957/// ParseEnumBody - Parse a {} enclosed enumerator-list.
1958///       enumerator-list:
1959///         enumerator
1960///         enumerator-list ',' enumerator
1961///       enumerator:
1962///         enumeration-constant
1963///         enumeration-constant '=' constant-expression
1964///       enumeration-constant:
1965///         identifier
1966///
1967void Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) {
1968  // Enter the scope of the enum body and start the definition.
1969  ParseScope EnumScope(this, Scope::DeclScope);
1970  Actions.ActOnTagStartDefinition(CurScope, EnumDecl);
1971
1972  SourceLocation LBraceLoc = ConsumeBrace();
1973
1974  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
1975  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1976    Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
1977
1978  llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls;
1979
1980  DeclPtrTy LastEnumConstDecl;
1981
1982  // Parse the enumerator-list.
1983  while (Tok.is(tok::identifier)) {
1984    IdentifierInfo *Ident = Tok.getIdentifierInfo();
1985    SourceLocation IdentLoc = ConsumeToken();
1986
1987    SourceLocation EqualLoc;
1988    OwningExprResult AssignedVal(Actions);
1989    if (Tok.is(tok::equal)) {
1990      EqualLoc = ConsumeToken();
1991      AssignedVal = ParseConstantExpression();
1992      if (AssignedVal.isInvalid())
1993        SkipUntil(tok::comma, tok::r_brace, true, true);
1994    }
1995
1996    // Install the enumerator constant into EnumDecl.
1997    DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1998                                                        LastEnumConstDecl,
1999                                                        IdentLoc, Ident,
2000                                                        EqualLoc,
2001                                                        AssignedVal.release());
2002    EnumConstantDecls.push_back(EnumConstDecl);
2003    LastEnumConstDecl = EnumConstDecl;
2004
2005    if (Tok.isNot(tok::comma))
2006      break;
2007    SourceLocation CommaLoc = ConsumeToken();
2008
2009    if (Tok.isNot(tok::identifier) &&
2010        !(getLang().C99 || getLang().CPlusPlus0x))
2011      Diag(CommaLoc, diag::ext_enumerator_list_comma)
2012        << getLang().CPlusPlus
2013        << FixItHint::CreateRemoval(CommaLoc);
2014  }
2015
2016  // Eat the }.
2017  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2018
2019  llvm::OwningPtr<AttributeList> Attr;
2020  // If attributes exist after the identifier list, parse them.
2021  if (Tok.is(tok::kw___attribute))
2022    Attr.reset(ParseGNUAttributes()); // FIXME: where do they do?
2023
2024  Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
2025                        EnumConstantDecls.data(), EnumConstantDecls.size(),
2026                        CurScope, Attr.get());
2027
2028  EnumScope.Exit();
2029  Actions.ActOnTagFinishDefinition(CurScope, EnumDecl, RBraceLoc);
2030}
2031
2032/// isTypeSpecifierQualifier - Return true if the current token could be the
2033/// start of a type-qualifier-list.
2034bool Parser::isTypeQualifier() const {
2035  switch (Tok.getKind()) {
2036  default: return false;
2037    // type-qualifier
2038  case tok::kw_const:
2039  case tok::kw_volatile:
2040  case tok::kw_restrict:
2041    return true;
2042  }
2043}
2044
2045/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2046/// is definitely a type-specifier.  Return false if it isn't part of a type
2047/// specifier or if we're not sure.
2048bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
2049  switch (Tok.getKind()) {
2050  default: return false;
2051    // type-specifiers
2052  case tok::kw_short:
2053  case tok::kw_long:
2054  case tok::kw_signed:
2055  case tok::kw_unsigned:
2056  case tok::kw__Complex:
2057  case tok::kw__Imaginary:
2058  case tok::kw_void:
2059  case tok::kw_char:
2060  case tok::kw_wchar_t:
2061  case tok::kw_char16_t:
2062  case tok::kw_char32_t:
2063  case tok::kw_int:
2064  case tok::kw_float:
2065  case tok::kw_double:
2066  case tok::kw_bool:
2067  case tok::kw__Bool:
2068  case tok::kw__Decimal32:
2069  case tok::kw__Decimal64:
2070  case tok::kw__Decimal128:
2071  case tok::kw___vector:
2072
2073    // struct-or-union-specifier (C99) or class-specifier (C++)
2074  case tok::kw_class:
2075  case tok::kw_struct:
2076  case tok::kw_union:
2077    // enum-specifier
2078  case tok::kw_enum:
2079
2080    // typedef-name
2081  case tok::annot_typename:
2082    return true;
2083  }
2084}
2085
2086/// isTypeSpecifierQualifier - Return true if the current token could be the
2087/// start of a specifier-qualifier-list.
2088bool Parser::isTypeSpecifierQualifier() {
2089  switch (Tok.getKind()) {
2090  default: return false;
2091
2092  case tok::identifier:   // foo::bar
2093    if (TryAltiVecVectorToken())
2094      return true;
2095    // Fall through.
2096  case tok::kw_typename:  // typename T::type
2097    // Annotate typenames and C++ scope specifiers.  If we get one, just
2098    // recurse to handle whatever we get.
2099    if (TryAnnotateTypeOrScopeToken())
2100      return true;
2101    if (Tok.is(tok::identifier))
2102      return false;
2103    return isTypeSpecifierQualifier();
2104
2105  case tok::coloncolon:   // ::foo::bar
2106    if (NextToken().is(tok::kw_new) ||    // ::new
2107        NextToken().is(tok::kw_delete))   // ::delete
2108      return false;
2109
2110    if (TryAnnotateTypeOrScopeToken())
2111      return true;
2112    return isTypeSpecifierQualifier();
2113
2114    // GNU attributes support.
2115  case tok::kw___attribute:
2116    // GNU typeof support.
2117  case tok::kw_typeof:
2118
2119    // type-specifiers
2120  case tok::kw_short:
2121  case tok::kw_long:
2122  case tok::kw_signed:
2123  case tok::kw_unsigned:
2124  case tok::kw__Complex:
2125  case tok::kw__Imaginary:
2126  case tok::kw_void:
2127  case tok::kw_char:
2128  case tok::kw_wchar_t:
2129  case tok::kw_char16_t:
2130  case tok::kw_char32_t:
2131  case tok::kw_int:
2132  case tok::kw_float:
2133  case tok::kw_double:
2134  case tok::kw_bool:
2135  case tok::kw__Bool:
2136  case tok::kw__Decimal32:
2137  case tok::kw__Decimal64:
2138  case tok::kw__Decimal128:
2139  case tok::kw___vector:
2140
2141    // struct-or-union-specifier (C99) or class-specifier (C++)
2142  case tok::kw_class:
2143  case tok::kw_struct:
2144  case tok::kw_union:
2145    // enum-specifier
2146  case tok::kw_enum:
2147
2148    // type-qualifier
2149  case tok::kw_const:
2150  case tok::kw_volatile:
2151  case tok::kw_restrict:
2152
2153    // typedef-name
2154  case tok::annot_typename:
2155    return true;
2156
2157    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2158  case tok::less:
2159    return getLang().ObjC1;
2160
2161  case tok::kw___cdecl:
2162  case tok::kw___stdcall:
2163  case tok::kw___fastcall:
2164  case tok::kw___w64:
2165  case tok::kw___ptr64:
2166    return true;
2167  }
2168}
2169
2170/// isDeclarationSpecifier() - Return true if the current token is part of a
2171/// declaration specifier.
2172bool Parser::isDeclarationSpecifier() {
2173  switch (Tok.getKind()) {
2174  default: return false;
2175
2176  case tok::identifier:   // foo::bar
2177    // Unfortunate hack to support "Class.factoryMethod" notation.
2178    if (getLang().ObjC1 && NextToken().is(tok::period))
2179      return false;
2180    if (TryAltiVecVectorToken())
2181      return true;
2182    // Fall through.
2183  case tok::kw_typename: // typename T::type
2184    // Annotate typenames and C++ scope specifiers.  If we get one, just
2185    // recurse to handle whatever we get.
2186    if (TryAnnotateTypeOrScopeToken())
2187      return true;
2188    if (Tok.is(tok::identifier))
2189      return false;
2190    return isDeclarationSpecifier();
2191
2192  case tok::coloncolon:   // ::foo::bar
2193    if (NextToken().is(tok::kw_new) ||    // ::new
2194        NextToken().is(tok::kw_delete))   // ::delete
2195      return false;
2196
2197    // Annotate typenames and C++ scope specifiers.  If we get one, just
2198    // recurse to handle whatever we get.
2199    if (TryAnnotateTypeOrScopeToken())
2200      return true;
2201    return isDeclarationSpecifier();
2202
2203    // storage-class-specifier
2204  case tok::kw_typedef:
2205  case tok::kw_extern:
2206  case tok::kw___private_extern__:
2207  case tok::kw_static:
2208  case tok::kw_auto:
2209  case tok::kw_register:
2210  case tok::kw___thread:
2211
2212    // type-specifiers
2213  case tok::kw_short:
2214  case tok::kw_long:
2215  case tok::kw_signed:
2216  case tok::kw_unsigned:
2217  case tok::kw__Complex:
2218  case tok::kw__Imaginary:
2219  case tok::kw_void:
2220  case tok::kw_char:
2221  case tok::kw_wchar_t:
2222  case tok::kw_char16_t:
2223  case tok::kw_char32_t:
2224
2225  case tok::kw_int:
2226  case tok::kw_float:
2227  case tok::kw_double:
2228  case tok::kw_bool:
2229  case tok::kw__Bool:
2230  case tok::kw__Decimal32:
2231  case tok::kw__Decimal64:
2232  case tok::kw__Decimal128:
2233  case tok::kw___vector:
2234
2235    // struct-or-union-specifier (C99) or class-specifier (C++)
2236  case tok::kw_class:
2237  case tok::kw_struct:
2238  case tok::kw_union:
2239    // enum-specifier
2240  case tok::kw_enum:
2241
2242    // type-qualifier
2243  case tok::kw_const:
2244  case tok::kw_volatile:
2245  case tok::kw_restrict:
2246
2247    // function-specifier
2248  case tok::kw_inline:
2249  case tok::kw_virtual:
2250  case tok::kw_explicit:
2251
2252    // typedef-name
2253  case tok::annot_typename:
2254
2255    // GNU typeof support.
2256  case tok::kw_typeof:
2257
2258    // GNU attributes.
2259  case tok::kw___attribute:
2260    return true;
2261
2262    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2263  case tok::less:
2264    return getLang().ObjC1;
2265
2266  case tok::kw___declspec:
2267  case tok::kw___cdecl:
2268  case tok::kw___stdcall:
2269  case tok::kw___fastcall:
2270  case tok::kw___w64:
2271  case tok::kw___ptr64:
2272  case tok::kw___forceinline:
2273    return true;
2274  }
2275}
2276
2277bool Parser::isConstructorDeclarator() {
2278  TentativeParsingAction TPA(*this);
2279
2280  // Parse the C++ scope specifier.
2281  CXXScopeSpec SS;
2282  if (ParseOptionalCXXScopeSpecifier(SS, 0, true)) {
2283    TPA.Revert();
2284    return false;
2285  }
2286
2287  // Parse the constructor name.
2288  if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
2289    // We already know that we have a constructor name; just consume
2290    // the token.
2291    ConsumeToken();
2292  } else {
2293    TPA.Revert();
2294    return false;
2295  }
2296
2297  // Current class name must be followed by a left parentheses.
2298  if (Tok.isNot(tok::l_paren)) {
2299    TPA.Revert();
2300    return false;
2301  }
2302  ConsumeParen();
2303
2304  // A right parentheses or ellipsis signals that we have a constructor.
2305  if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
2306    TPA.Revert();
2307    return true;
2308  }
2309
2310  // If we need to, enter the specified scope.
2311  DeclaratorScopeObj DeclScopeObj(*this, SS);
2312  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(CurScope, SS))
2313    DeclScopeObj.EnterDeclaratorScope();
2314
2315  // Check whether the next token(s) are part of a declaration
2316  // specifier, in which case we have the start of a parameter and,
2317  // therefore, we know that this is a constructor.
2318  bool IsConstructor = isDeclarationSpecifier();
2319  TPA.Revert();
2320  return IsConstructor;
2321}
2322
2323/// ParseTypeQualifierListOpt
2324///       type-qualifier-list: [C99 6.7.5]
2325///         type-qualifier
2326/// [GNU]   attributes                        [ only if AttributesAllowed=true ]
2327///         type-qualifier-list type-qualifier
2328/// [GNU]   type-qualifier-list attributes    [ only if AttributesAllowed=true ]
2329/// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
2330///           if CXX0XAttributesAllowed = true
2331///
2332void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed,
2333                                       bool CXX0XAttributesAllowed) {
2334  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
2335    SourceLocation Loc = Tok.getLocation();
2336    CXX0XAttributeList Attr = ParseCXX0XAttributes();
2337    if (CXX0XAttributesAllowed)
2338      DS.AddAttributes(Attr.AttrList);
2339    else
2340      Diag(Loc, diag::err_attributes_not_allowed);
2341  }
2342
2343  while (1) {
2344    bool isInvalid = false;
2345    const char *PrevSpec = 0;
2346    unsigned DiagID = 0;
2347    SourceLocation Loc = Tok.getLocation();
2348
2349    switch (Tok.getKind()) {
2350    case tok::kw_const:
2351      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
2352                                 getLang());
2353      break;
2354    case tok::kw_volatile:
2355      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
2356                                 getLang());
2357      break;
2358    case tok::kw_restrict:
2359      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
2360                                 getLang());
2361      break;
2362    case tok::kw___w64:
2363    case tok::kw___ptr64:
2364    case tok::kw___cdecl:
2365    case tok::kw___stdcall:
2366    case tok::kw___fastcall:
2367      if (GNUAttributesAllowed) {
2368        DS.AddAttributes(ParseMicrosoftTypeAttributes());
2369        continue;
2370      }
2371      goto DoneWithTypeQuals;
2372    case tok::kw___attribute:
2373      if (GNUAttributesAllowed) {
2374        DS.AddAttributes(ParseGNUAttributes());
2375        continue; // do *not* consume the next token!
2376      }
2377      // otherwise, FALL THROUGH!
2378    default:
2379      DoneWithTypeQuals:
2380      // If this is not a type-qualifier token, we're done reading type
2381      // qualifiers.  First verify that DeclSpec's are consistent.
2382      DS.Finish(Diags, PP);
2383      return;
2384    }
2385
2386    // If the specifier combination wasn't legal, issue a diagnostic.
2387    if (isInvalid) {
2388      assert(PrevSpec && "Method did not return previous specifier!");
2389      Diag(Tok, DiagID) << PrevSpec;
2390    }
2391    ConsumeToken();
2392  }
2393}
2394
2395
2396/// ParseDeclarator - Parse and verify a newly-initialized declarator.
2397///
2398void Parser::ParseDeclarator(Declarator &D) {
2399  /// This implements the 'declarator' production in the C grammar, then checks
2400  /// for well-formedness and issues diagnostics.
2401  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2402}
2403
2404/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
2405/// is parsed by the function passed to it. Pass null, and the direct-declarator
2406/// isn't parsed at all, making this function effectively parse the C++
2407/// ptr-operator production.
2408///
2409///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
2410/// [C]     pointer[opt] direct-declarator
2411/// [C++]   direct-declarator
2412/// [C++]   ptr-operator declarator
2413///
2414///       pointer: [C99 6.7.5]
2415///         '*' type-qualifier-list[opt]
2416///         '*' type-qualifier-list[opt] pointer
2417///
2418///       ptr-operator:
2419///         '*' cv-qualifier-seq[opt]
2420///         '&'
2421/// [C++0x] '&&'
2422/// [GNU]   '&' restrict[opt] attributes[opt]
2423/// [GNU?]  '&&' restrict[opt] attributes[opt]
2424///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
2425void Parser::ParseDeclaratorInternal(Declarator &D,
2426                                     DirectDeclParseFunction DirectDeclParser) {
2427  if (Diags.hasAllExtensionsSilenced())
2428    D.setExtension();
2429  // C++ member pointers start with a '::' or a nested-name.
2430  // Member pointers get special handling, since there's no place for the
2431  // scope spec in the generic path below.
2432  if (getLang().CPlusPlus &&
2433      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
2434       Tok.is(tok::annot_cxxscope))) {
2435    CXXScopeSpec SS;
2436    ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true); // ignore fail
2437
2438    if (SS.isNotEmpty()) {
2439      if (Tok.isNot(tok::star)) {
2440        // The scope spec really belongs to the direct-declarator.
2441        D.getCXXScopeSpec() = SS;
2442        if (DirectDeclParser)
2443          (this->*DirectDeclParser)(D);
2444        return;
2445      }
2446
2447      SourceLocation Loc = ConsumeToken();
2448      D.SetRangeEnd(Loc);
2449      DeclSpec DS;
2450      ParseTypeQualifierListOpt(DS);
2451      D.ExtendWithDeclSpec(DS);
2452
2453      // Recurse to parse whatever is left.
2454      ParseDeclaratorInternal(D, DirectDeclParser);
2455
2456      // Sema will have to catch (syntactically invalid) pointers into global
2457      // scope. It has to catch pointers into namespace scope anyway.
2458      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
2459                                                      Loc, DS.TakeAttributes()),
2460                    /* Don't replace range end. */SourceLocation());
2461      return;
2462    }
2463  }
2464
2465  tok::TokenKind Kind = Tok.getKind();
2466  // Not a pointer, C++ reference, or block.
2467  if (Kind != tok::star && Kind != tok::caret &&
2468      (Kind != tok::amp || !getLang().CPlusPlus) &&
2469      // We parse rvalue refs in C++03, because otherwise the errors are scary.
2470      (Kind != tok::ampamp || !getLang().CPlusPlus)) {
2471    if (DirectDeclParser)
2472      (this->*DirectDeclParser)(D);
2473    return;
2474  }
2475
2476  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
2477  // '&&' -> rvalue reference
2478  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
2479  D.SetRangeEnd(Loc);
2480
2481  if (Kind == tok::star || Kind == tok::caret) {
2482    // Is a pointer.
2483    DeclSpec DS;
2484
2485    ParseTypeQualifierListOpt(DS);
2486    D.ExtendWithDeclSpec(DS);
2487
2488    // Recursively parse the declarator.
2489    ParseDeclaratorInternal(D, DirectDeclParser);
2490    if (Kind == tok::star)
2491      // Remember that we parsed a pointer type, and remember the type-quals.
2492      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
2493                                                DS.TakeAttributes()),
2494                    SourceLocation());
2495    else
2496      // Remember that we parsed a Block type, and remember the type-quals.
2497      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
2498                                                     Loc, DS.TakeAttributes()),
2499                    SourceLocation());
2500  } else {
2501    // Is a reference
2502    DeclSpec DS;
2503
2504    // Complain about rvalue references in C++03, but then go on and build
2505    // the declarator.
2506    if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
2507      Diag(Loc, diag::err_rvalue_reference);
2508
2509    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
2510    // cv-qualifiers are introduced through the use of a typedef or of a
2511    // template type argument, in which case the cv-qualifiers are ignored.
2512    //
2513    // [GNU] Retricted references are allowed.
2514    // [GNU] Attributes on references are allowed.
2515    // [C++0x] Attributes on references are not allowed.
2516    ParseTypeQualifierListOpt(DS, true, false);
2517    D.ExtendWithDeclSpec(DS);
2518
2519    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2520      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2521        Diag(DS.getConstSpecLoc(),
2522             diag::err_invalid_reference_qualifier_application) << "const";
2523      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2524        Diag(DS.getVolatileSpecLoc(),
2525             diag::err_invalid_reference_qualifier_application) << "volatile";
2526    }
2527
2528    // Recursively parse the declarator.
2529    ParseDeclaratorInternal(D, DirectDeclParser);
2530
2531    if (D.getNumTypeObjects() > 0) {
2532      // C++ [dcl.ref]p4: There shall be no references to references.
2533      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
2534      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
2535        if (const IdentifierInfo *II = D.getIdentifier())
2536          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2537           << II;
2538        else
2539          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2540            << "type name";
2541
2542        // Once we've complained about the reference-to-reference, we
2543        // can go ahead and build the (technically ill-formed)
2544        // declarator: reference collapsing will take care of it.
2545      }
2546    }
2547
2548    // Remember that we parsed a reference type. It doesn't have type-quals.
2549    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
2550                                                DS.TakeAttributes(),
2551                                                Kind == tok::amp),
2552                  SourceLocation());
2553  }
2554}
2555
2556/// ParseDirectDeclarator
2557///       direct-declarator: [C99 6.7.5]
2558/// [C99]   identifier
2559///         '(' declarator ')'
2560/// [GNU]   '(' attributes declarator ')'
2561/// [C90]   direct-declarator '[' constant-expression[opt] ']'
2562/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2563/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2564/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2565/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
2566///         direct-declarator '(' parameter-type-list ')'
2567///         direct-declarator '(' identifier-list[opt] ')'
2568/// [GNU]   direct-declarator '(' parameter-forward-declarations
2569///                    parameter-type-list[opt] ')'
2570/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
2571///                    cv-qualifier-seq[opt] exception-specification[opt]
2572/// [C++]   declarator-id
2573///
2574///       declarator-id: [C++ 8]
2575///         id-expression
2576///         '::'[opt] nested-name-specifier[opt] type-name
2577///
2578///       id-expression: [C++ 5.1]
2579///         unqualified-id
2580///         qualified-id
2581///
2582///       unqualified-id: [C++ 5.1]
2583///         identifier
2584///         operator-function-id
2585///         conversion-function-id
2586///          '~' class-name
2587///         template-id
2588///
2589void Parser::ParseDirectDeclarator(Declarator &D) {
2590  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
2591
2592  if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
2593    // ParseDeclaratorInternal might already have parsed the scope.
2594    if (D.getCXXScopeSpec().isEmpty()) {
2595      ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), /*ObjectType=*/0,
2596                                     true);
2597    }
2598
2599    if (D.getCXXScopeSpec().isValid()) {
2600      if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec()))
2601        // Change the declaration context for name lookup, until this function
2602        // is exited (and the declarator has been parsed).
2603        DeclScopeObj.EnterDeclaratorScope();
2604    }
2605
2606    if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
2607        Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
2608      // We found something that indicates the start of an unqualified-id.
2609      // Parse that unqualified-id.
2610      bool AllowConstructorName;
2611      if (D.getDeclSpec().hasTypeSpecifier())
2612        AllowConstructorName = false;
2613      else if (D.getCXXScopeSpec().isSet())
2614        AllowConstructorName =
2615          (D.getContext() == Declarator::FileContext ||
2616           (D.getContext() == Declarator::MemberContext &&
2617            D.getDeclSpec().isFriendSpecified()));
2618      else
2619        AllowConstructorName = (D.getContext() == Declarator::MemberContext);
2620
2621      if (ParseUnqualifiedId(D.getCXXScopeSpec(),
2622                             /*EnteringContext=*/true,
2623                             /*AllowDestructorName=*/true,
2624                             AllowConstructorName,
2625                             /*ObjectType=*/0,
2626                             D.getName()) ||
2627          // Once we're past the identifier, if the scope was bad, mark the
2628          // whole declarator bad.
2629          D.getCXXScopeSpec().isInvalid()) {
2630        D.SetIdentifier(0, Tok.getLocation());
2631        D.setInvalidType(true);
2632      } else {
2633        // Parsed the unqualified-id; update range information and move along.
2634        if (D.getSourceRange().getBegin().isInvalid())
2635          D.SetRangeBegin(D.getName().getSourceRange().getBegin());
2636        D.SetRangeEnd(D.getName().getSourceRange().getEnd());
2637      }
2638      goto PastIdentifier;
2639    }
2640  } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
2641    assert(!getLang().CPlusPlus &&
2642           "There's a C++-specific check for tok::identifier above");
2643    assert(Tok.getIdentifierInfo() && "Not an identifier?");
2644    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2645    ConsumeToken();
2646    goto PastIdentifier;
2647  }
2648
2649  if (Tok.is(tok::l_paren)) {
2650    // direct-declarator: '(' declarator ')'
2651    // direct-declarator: '(' attributes declarator ')'
2652    // Example: 'char (*X)'   or 'int (*XX)(void)'
2653    ParseParenDeclarator(D);
2654
2655    // If the declarator was parenthesized, we entered the declarator
2656    // scope when parsing the parenthesized declarator, then exited
2657    // the scope already. Re-enter the scope, if we need to.
2658    if (D.getCXXScopeSpec().isSet()) {
2659      if (Actions.ShouldEnterDeclaratorScope(CurScope, D.getCXXScopeSpec()))
2660        // Change the declaration context for name lookup, until this function
2661        // is exited (and the declarator has been parsed).
2662        DeclScopeObj.EnterDeclaratorScope();
2663    }
2664  } else if (D.mayOmitIdentifier()) {
2665    // This could be something simple like "int" (in which case the declarator
2666    // portion is empty), if an abstract-declarator is allowed.
2667    D.SetIdentifier(0, Tok.getLocation());
2668  } else {
2669    if (D.getContext() == Declarator::MemberContext)
2670      Diag(Tok, diag::err_expected_member_name_or_semi)
2671        << D.getDeclSpec().getSourceRange();
2672    else if (getLang().CPlusPlus)
2673      Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
2674    else
2675      Diag(Tok, diag::err_expected_ident_lparen);
2676    D.SetIdentifier(0, Tok.getLocation());
2677    D.setInvalidType(true);
2678  }
2679
2680 PastIdentifier:
2681  assert(D.isPastIdentifier() &&
2682         "Haven't past the location of the identifier yet?");
2683
2684  // Don't parse attributes unless we have an identifier.
2685  if (D.getIdentifier() && getLang().CPlusPlus0x
2686   && isCXX0XAttributeSpecifier(true)) {
2687    SourceLocation AttrEndLoc;
2688    CXX0XAttributeList Attr = ParseCXX0XAttributes();
2689    D.AddAttributes(Attr.AttrList, AttrEndLoc);
2690  }
2691
2692  while (1) {
2693    if (Tok.is(tok::l_paren)) {
2694      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
2695      // In such a case, check if we actually have a function declarator; if it
2696      // is not, the declarator has been fully parsed.
2697      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
2698        // When not in file scope, warn for ambiguous function declarators, just
2699        // in case the author intended it as a variable definition.
2700        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
2701        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
2702          break;
2703      }
2704      ParseFunctionDeclarator(ConsumeParen(), D);
2705    } else if (Tok.is(tok::l_square)) {
2706      ParseBracketDeclarator(D);
2707    } else {
2708      break;
2709    }
2710  }
2711}
2712
2713/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
2714/// only called before the identifier, so these are most likely just grouping
2715/// parens for precedence.  If we find that these are actually function
2716/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
2717///
2718///       direct-declarator:
2719///         '(' declarator ')'
2720/// [GNU]   '(' attributes declarator ')'
2721///         direct-declarator '(' parameter-type-list ')'
2722///         direct-declarator '(' identifier-list[opt] ')'
2723/// [GNU]   direct-declarator '(' parameter-forward-declarations
2724///                    parameter-type-list[opt] ')'
2725///
2726void Parser::ParseParenDeclarator(Declarator &D) {
2727  SourceLocation StartLoc = ConsumeParen();
2728  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
2729
2730  // Eat any attributes before we look at whether this is a grouping or function
2731  // declarator paren.  If this is a grouping paren, the attribute applies to
2732  // the type being built up, for example:
2733  //     int (__attribute__(()) *x)(long y)
2734  // If this ends up not being a grouping paren, the attribute applies to the
2735  // first argument, for example:
2736  //     int (__attribute__(()) int x)
2737  // In either case, we need to eat any attributes to be able to determine what
2738  // sort of paren this is.
2739  //
2740  llvm::OwningPtr<AttributeList> AttrList;
2741  bool RequiresArg = false;
2742  if (Tok.is(tok::kw___attribute)) {
2743    AttrList.reset(ParseGNUAttributes());
2744
2745    // We require that the argument list (if this is a non-grouping paren) be
2746    // present even if the attribute list was empty.
2747    RequiresArg = true;
2748  }
2749  // Eat any Microsoft extensions.
2750  if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
2751       Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___w64) ||
2752       Tok.is(tok::kw___ptr64)) {
2753    AttrList.reset(ParseMicrosoftTypeAttributes(AttrList.take()));
2754  }
2755
2756  // If we haven't past the identifier yet (or where the identifier would be
2757  // stored, if this is an abstract declarator), then this is probably just
2758  // grouping parens. However, if this could be an abstract-declarator, then
2759  // this could also be the start of function arguments (consider 'void()').
2760  bool isGrouping;
2761
2762  if (!D.mayOmitIdentifier()) {
2763    // If this can't be an abstract-declarator, this *must* be a grouping
2764    // paren, because we haven't seen the identifier yet.
2765    isGrouping = true;
2766  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
2767             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
2768             isDeclarationSpecifier()) {       // 'int(int)' is a function.
2769    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
2770    // considered to be a type, not a K&R identifier-list.
2771    isGrouping = false;
2772  } else {
2773    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
2774    isGrouping = true;
2775  }
2776
2777  // If this is a grouping paren, handle:
2778  // direct-declarator: '(' declarator ')'
2779  // direct-declarator: '(' attributes declarator ')'
2780  if (isGrouping) {
2781    bool hadGroupingParens = D.hasGroupingParens();
2782    D.setGroupingParens(true);
2783    if (AttrList)
2784      D.AddAttributes(AttrList.take(), SourceLocation());
2785
2786    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2787    // Match the ')'.
2788    SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc);
2789
2790    D.setGroupingParens(hadGroupingParens);
2791    D.SetRangeEnd(Loc);
2792    return;
2793  }
2794
2795  // Okay, if this wasn't a grouping paren, it must be the start of a function
2796  // argument list.  Recognize that this declarator will never have an
2797  // identifier (and remember where it would have been), then call into
2798  // ParseFunctionDeclarator to handle of argument list.
2799  D.SetIdentifier(0, Tok.getLocation());
2800
2801  ParseFunctionDeclarator(StartLoc, D, AttrList.take(), RequiresArg);
2802}
2803
2804/// ParseFunctionDeclarator - We are after the identifier and have parsed the
2805/// declarator D up to a paren, which indicates that we are parsing function
2806/// arguments.
2807///
2808/// If AttrList is non-null, then the caller parsed those arguments immediately
2809/// after the open paren - they should be considered to be the first argument of
2810/// a parameter.  If RequiresArg is true, then the first argument of the
2811/// function is required to be present and required to not be an identifier
2812/// list.
2813///
2814/// This method also handles this portion of the grammar:
2815///       parameter-type-list: [C99 6.7.5]
2816///         parameter-list
2817///         parameter-list ',' '...'
2818/// [C++]   parameter-list '...'
2819///
2820///       parameter-list: [C99 6.7.5]
2821///         parameter-declaration
2822///         parameter-list ',' parameter-declaration
2823///
2824///       parameter-declaration: [C99 6.7.5]
2825///         declaration-specifiers declarator
2826/// [C++]   declaration-specifiers declarator '=' assignment-expression
2827/// [GNU]   declaration-specifiers declarator attributes
2828///         declaration-specifiers abstract-declarator[opt]
2829/// [C++]   declaration-specifiers abstract-declarator[opt]
2830///           '=' assignment-expression
2831/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
2832///
2833/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
2834/// and "exception-specification[opt]".
2835///
2836void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
2837                                     AttributeList *AttrList,
2838                                     bool RequiresArg) {
2839  // lparen is already consumed!
2840  assert(D.isPastIdentifier() && "Should not call before identifier!");
2841
2842  // This parameter list may be empty.
2843  if (Tok.is(tok::r_paren)) {
2844    if (RequiresArg) {
2845      Diag(Tok, diag::err_argument_required_after_attribute);
2846      delete AttrList;
2847    }
2848
2849    SourceLocation RParenLoc = ConsumeParen();  // Eat the closing ')'.
2850    SourceLocation EndLoc = RParenLoc;
2851
2852    // cv-qualifier-seq[opt].
2853    DeclSpec DS;
2854    bool hasExceptionSpec = false;
2855    SourceLocation ThrowLoc;
2856    bool hasAnyExceptionSpec = false;
2857    llvm::SmallVector<TypeTy*, 2> Exceptions;
2858    llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2859    if (getLang().CPlusPlus) {
2860      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2861      if (!DS.getSourceRange().getEnd().isInvalid())
2862        EndLoc = DS.getSourceRange().getEnd();
2863
2864      // Parse exception-specification[opt].
2865      if (Tok.is(tok::kw_throw)) {
2866        hasExceptionSpec = true;
2867        ThrowLoc = Tok.getLocation();
2868        ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
2869                                    hasAnyExceptionSpec);
2870        assert(Exceptions.size() == ExceptionRanges.size() &&
2871               "Produced different number of exception types and ranges.");
2872      }
2873    }
2874
2875    // Remember that we parsed a function type, and remember the attributes.
2876    // int() -> no prototype, no '...'.
2877    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
2878                                               /*variadic*/ false,
2879                                               SourceLocation(),
2880                                               /*arglist*/ 0, 0,
2881                                               DS.getTypeQualifiers(),
2882                                               hasExceptionSpec, ThrowLoc,
2883                                               hasAnyExceptionSpec,
2884                                               Exceptions.data(),
2885                                               ExceptionRanges.data(),
2886                                               Exceptions.size(),
2887                                               LParenLoc, RParenLoc, D),
2888                  EndLoc);
2889    return;
2890  }
2891
2892  // Alternatively, this parameter list may be an identifier list form for a
2893  // K&R-style function:  void foo(a,b,c)
2894  if (!getLang().CPlusPlus && Tok.is(tok::identifier)
2895      && !TryAltiVecVectorToken()) {
2896    if (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) {
2897      // K&R identifier lists can't have typedefs as identifiers, per
2898      // C99 6.7.5.3p11.
2899      if (RequiresArg) {
2900        Diag(Tok, diag::err_argument_required_after_attribute);
2901        delete AttrList;
2902      }
2903      // Identifier list.  Note that '(' identifier-list ')' is only allowed for
2904      // normal declarators, not for abstract-declarators.
2905      return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
2906    }
2907  }
2908
2909  // Finally, a normal, non-empty parameter type list.
2910
2911  // Build up an array of information about the parsed arguments.
2912  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2913
2914  // Enter function-declaration scope, limiting any declarators to the
2915  // function prototype scope, including parameter declarators.
2916  ParseScope PrototypeScope(this,
2917                            Scope::FunctionPrototypeScope|Scope::DeclScope);
2918
2919  bool IsVariadic = false;
2920  SourceLocation EllipsisLoc;
2921  while (1) {
2922    if (Tok.is(tok::ellipsis)) {
2923      IsVariadic = true;
2924      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
2925      break;
2926    }
2927
2928    SourceLocation DSStart = Tok.getLocation();
2929
2930    // Parse the declaration-specifiers.
2931    // Just use the ParsingDeclaration "scope" of the declarator.
2932    DeclSpec DS;
2933
2934    // If the caller parsed attributes for the first argument, add them now.
2935    if (AttrList) {
2936      DS.AddAttributes(AttrList);
2937      AttrList = 0;  // Only apply the attributes to the first parameter.
2938    }
2939    ParseDeclarationSpecifiers(DS);
2940
2941    // Parse the declarator.  This is "PrototypeContext", because we must
2942    // accept either 'declarator' or 'abstract-declarator' here.
2943    Declarator ParmDecl(DS, Declarator::PrototypeContext);
2944    ParseDeclarator(ParmDecl);
2945
2946    // Parse GNU attributes, if present.
2947    if (Tok.is(tok::kw___attribute)) {
2948      SourceLocation Loc;
2949      AttributeList *AttrList = ParseGNUAttributes(&Loc);
2950      ParmDecl.AddAttributes(AttrList, Loc);
2951    }
2952
2953    // Remember this parsed parameter in ParamInfo.
2954    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
2955
2956    // DefArgToks is used when the parsing of default arguments needs
2957    // to be delayed.
2958    CachedTokens *DefArgToks = 0;
2959
2960    // If no parameter was specified, verify that *something* was specified,
2961    // otherwise we have a missing type and identifier.
2962    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
2963        ParmDecl.getNumTypeObjects() == 0) {
2964      // Completely missing, emit error.
2965      Diag(DSStart, diag::err_missing_param);
2966    } else {
2967      // Otherwise, we have something.  Add it and let semantic analysis try
2968      // to grok it and add the result to the ParamInfo we are building.
2969
2970      // Inform the actions module about the parameter declarator, so it gets
2971      // added to the current scope.
2972      DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
2973
2974      // Parse the default argument, if any. We parse the default
2975      // arguments in all dialects; the semantic analysis in
2976      // ActOnParamDefaultArgument will reject the default argument in
2977      // C.
2978      if (Tok.is(tok::equal)) {
2979        SourceLocation EqualLoc = Tok.getLocation();
2980
2981        // Parse the default argument
2982        if (D.getContext() == Declarator::MemberContext) {
2983          // If we're inside a class definition, cache the tokens
2984          // corresponding to the default argument. We'll actually parse
2985          // them when we see the end of the class definition.
2986          // FIXME: Templates will require something similar.
2987          // FIXME: Can we use a smart pointer for Toks?
2988          DefArgToks = new CachedTokens;
2989
2990          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
2991                                    /*StopAtSemi=*/true,
2992                                    /*ConsumeFinalToken=*/false)) {
2993            delete DefArgToks;
2994            DefArgToks = 0;
2995            Actions.ActOnParamDefaultArgumentError(Param);
2996          } else
2997            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
2998                                                (*DefArgToks)[1].getLocation());
2999        } else {
3000          // Consume the '='.
3001          ConsumeToken();
3002
3003          OwningExprResult DefArgResult(ParseAssignmentExpression());
3004          if (DefArgResult.isInvalid()) {
3005            Actions.ActOnParamDefaultArgumentError(Param);
3006            SkipUntil(tok::comma, tok::r_paren, true, true);
3007          } else {
3008            // Inform the actions module about the default argument
3009            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
3010                                              move(DefArgResult));
3011          }
3012        }
3013      }
3014
3015      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3016                                          ParmDecl.getIdentifierLoc(), Param,
3017                                          DefArgToks));
3018    }
3019
3020    // If the next token is a comma, consume it and keep reading arguments.
3021    if (Tok.isNot(tok::comma)) {
3022      if (Tok.is(tok::ellipsis)) {
3023        IsVariadic = true;
3024        EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
3025
3026        if (!getLang().CPlusPlus) {
3027          // We have ellipsis without a preceding ',', which is ill-formed
3028          // in C. Complain and provide the fix.
3029          Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
3030            << FixItHint::CreateInsertion(EllipsisLoc, ", ");
3031        }
3032      }
3033
3034      break;
3035    }
3036
3037    // Consume the comma.
3038    ConsumeToken();
3039  }
3040
3041  // Leave prototype scope.
3042  PrototypeScope.Exit();
3043
3044  // If we have the closing ')', eat it.
3045  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3046  SourceLocation EndLoc = RParenLoc;
3047
3048  DeclSpec DS;
3049  bool hasExceptionSpec = false;
3050  SourceLocation ThrowLoc;
3051  bool hasAnyExceptionSpec = false;
3052  llvm::SmallVector<TypeTy*, 2> Exceptions;
3053  llvm::SmallVector<SourceRange, 2> ExceptionRanges;
3054
3055  if (getLang().CPlusPlus) {
3056    // Parse cv-qualifier-seq[opt].
3057    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3058      if (!DS.getSourceRange().getEnd().isInvalid())
3059        EndLoc = DS.getSourceRange().getEnd();
3060
3061    // Parse exception-specification[opt].
3062    if (Tok.is(tok::kw_throw)) {
3063      hasExceptionSpec = true;
3064      ThrowLoc = Tok.getLocation();
3065      ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
3066                                  hasAnyExceptionSpec);
3067      assert(Exceptions.size() == ExceptionRanges.size() &&
3068             "Produced different number of exception types and ranges.");
3069    }
3070  }
3071
3072  // Remember that we parsed a function type, and remember the attributes.
3073  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
3074                                             EllipsisLoc,
3075                                             ParamInfo.data(), ParamInfo.size(),
3076                                             DS.getTypeQualifiers(),
3077                                             hasExceptionSpec, ThrowLoc,
3078                                             hasAnyExceptionSpec,
3079                                             Exceptions.data(),
3080                                             ExceptionRanges.data(),
3081                                             Exceptions.size(),
3082                                             LParenLoc, RParenLoc, D),
3083                EndLoc);
3084}
3085
3086/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
3087/// we found a K&R-style identifier list instead of a type argument list.  The
3088/// current token is known to be the first identifier in the list.
3089///
3090///       identifier-list: [C99 6.7.5]
3091///         identifier
3092///         identifier-list ',' identifier
3093///
3094void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
3095                                                   Declarator &D) {
3096  // Build up an array of information about the parsed arguments.
3097  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3098  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
3099
3100  // If there was no identifier specified for the declarator, either we are in
3101  // an abstract-declarator, or we are in a parameter declarator which was found
3102  // to be abstract.  In abstract-declarators, identifier lists are not valid:
3103  // diagnose this.
3104  if (!D.getIdentifier())
3105    Diag(Tok, diag::ext_ident_list_in_param);
3106
3107  // Tok is known to be the first identifier in the list.  Remember this
3108  // identifier in ParamInfo.
3109  ParamsSoFar.insert(Tok.getIdentifierInfo());
3110  ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
3111                                                 Tok.getLocation(),
3112                                                 DeclPtrTy()));
3113
3114  ConsumeToken();  // eat the first identifier.
3115
3116  while (Tok.is(tok::comma)) {
3117    // Eat the comma.
3118    ConsumeToken();
3119
3120    // If this isn't an identifier, report the error and skip until ')'.
3121    if (Tok.isNot(tok::identifier)) {
3122      Diag(Tok, diag::err_expected_ident);
3123      SkipUntil(tok::r_paren);
3124      return;
3125    }
3126
3127    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
3128
3129    // Reject 'typedef int y; int test(x, y)', but continue parsing.
3130    if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope))
3131      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
3132
3133    // Verify that the argument identifier has not already been mentioned.
3134    if (!ParamsSoFar.insert(ParmII)) {
3135      Diag(Tok, diag::err_param_redefinition) << ParmII;
3136    } else {
3137      // Remember this identifier in ParamInfo.
3138      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3139                                                     Tok.getLocation(),
3140                                                     DeclPtrTy()));
3141    }
3142
3143    // Eat the identifier.
3144    ConsumeToken();
3145  }
3146
3147  // If we have the closing ')', eat it and we're done.
3148  SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3149
3150  // Remember that we parsed a function type, and remember the attributes.  This
3151  // function type is always a K&R style function type, which is not varargs and
3152  // has no prototype.
3153  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
3154                                             SourceLocation(),
3155                                             &ParamInfo[0], ParamInfo.size(),
3156                                             /*TypeQuals*/0,
3157                                             /*exception*/false,
3158                                             SourceLocation(), false, 0, 0, 0,
3159                                             LParenLoc, RLoc, D),
3160                RLoc);
3161}
3162
3163/// [C90]   direct-declarator '[' constant-expression[opt] ']'
3164/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3165/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3166/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3167/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
3168void Parser::ParseBracketDeclarator(Declarator &D) {
3169  SourceLocation StartLoc = ConsumeBracket();
3170
3171  // C array syntax has many features, but by-far the most common is [] and [4].
3172  // This code does a fast path to handle some of the most obvious cases.
3173  if (Tok.getKind() == tok::r_square) {
3174    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3175    //FIXME: Use these
3176    CXX0XAttributeList Attr;
3177    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier(true)) {
3178      Attr = ParseCXX0XAttributes();
3179    }
3180
3181    // Remember that we parsed the empty array type.
3182    OwningExprResult NumElements(Actions);
3183    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
3184                                            StartLoc, EndLoc),
3185                  EndLoc);
3186    return;
3187  } else if (Tok.getKind() == tok::numeric_constant &&
3188             GetLookAheadToken(1).is(tok::r_square)) {
3189    // [4] is very common.  Parse the numeric constant expression.
3190    OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
3191    ConsumeToken();
3192
3193    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3194    //FIXME: Use these
3195    CXX0XAttributeList Attr;
3196    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3197      Attr = ParseCXX0XAttributes();
3198    }
3199
3200    // If there was an error parsing the assignment-expression, recover.
3201    if (ExprRes.isInvalid())
3202      ExprRes.release();  // Deallocate expr, just use [].
3203
3204    // Remember that we parsed a array type, and remember its features.
3205    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(),
3206                                            StartLoc, EndLoc),
3207                  EndLoc);
3208    return;
3209  }
3210
3211  // If valid, this location is the position where we read the 'static' keyword.
3212  SourceLocation StaticLoc;
3213  if (Tok.is(tok::kw_static))
3214    StaticLoc = ConsumeToken();
3215
3216  // If there is a type-qualifier-list, read it now.
3217  // Type qualifiers in an array subscript are a C99 feature.
3218  DeclSpec DS;
3219  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3220
3221  // If we haven't already read 'static', check to see if there is one after the
3222  // type-qualifier-list.
3223  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
3224    StaticLoc = ConsumeToken();
3225
3226  // Handle "direct-declarator [ type-qual-list[opt] * ]".
3227  bool isStar = false;
3228  OwningExprResult NumElements(Actions);
3229
3230  // Handle the case where we have '[*]' as the array size.  However, a leading
3231  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
3232  // the the token after the star is a ']'.  Since stars in arrays are
3233  // infrequent, use of lookahead is not costly here.
3234  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
3235    ConsumeToken();  // Eat the '*'.
3236
3237    if (StaticLoc.isValid()) {
3238      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
3239      StaticLoc = SourceLocation();  // Drop the static.
3240    }
3241    isStar = true;
3242  } else if (Tok.isNot(tok::r_square)) {
3243    // Note, in C89, this production uses the constant-expr production instead
3244    // of assignment-expr.  The only difference is that assignment-expr allows
3245    // things like '=' and '*='.  Sema rejects these in C89 mode because they
3246    // are not i-c-e's, so we don't need to distinguish between the two here.
3247
3248    // Parse the constant-expression or assignment-expression now (depending
3249    // on dialect).
3250    if (getLang().CPlusPlus)
3251      NumElements = ParseConstantExpression();
3252    else
3253      NumElements = ParseAssignmentExpression();
3254  }
3255
3256  // If there was an error parsing the assignment-expression, recover.
3257  if (NumElements.isInvalid()) {
3258    D.setInvalidType(true);
3259    // If the expression was invalid, skip it.
3260    SkipUntil(tok::r_square);
3261    return;
3262  }
3263
3264  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3265
3266  //FIXME: Use these
3267  CXX0XAttributeList Attr;
3268  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
3269    Attr = ParseCXX0XAttributes();
3270  }
3271
3272  // Remember that we parsed a array type, and remember its features.
3273  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
3274                                          StaticLoc.isValid(), isStar,
3275                                          NumElements.release(),
3276                                          StartLoc, EndLoc),
3277                EndLoc);
3278}
3279
3280/// [GNU]   typeof-specifier:
3281///           typeof ( expressions )
3282///           typeof ( type-name )
3283/// [GNU/C++] typeof unary-expression
3284///
3285void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
3286  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
3287  Token OpTok = Tok;
3288  SourceLocation StartLoc = ConsumeToken();
3289
3290  const bool hasParens = Tok.is(tok::l_paren);
3291
3292  bool isCastExpr;
3293  TypeTy *CastTy;
3294  SourceRange CastRange;
3295  OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok,
3296                                                               isCastExpr,
3297                                                               CastTy,
3298                                                               CastRange);
3299  if (hasParens)
3300    DS.setTypeofParensRange(CastRange);
3301
3302  if (CastRange.getEnd().isInvalid())
3303    // FIXME: Not accurate, the range gets one token more than it should.
3304    DS.SetRangeEnd(Tok.getLocation());
3305  else
3306    DS.SetRangeEnd(CastRange.getEnd());
3307
3308  if (isCastExpr) {
3309    if (!CastTy) {
3310      DS.SetTypeSpecError();
3311      return;
3312    }
3313
3314    const char *PrevSpec = 0;
3315    unsigned DiagID;
3316    // Check for duplicate type specifiers (e.g. "int typeof(int)").
3317    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
3318                           DiagID, CastTy))
3319      Diag(StartLoc, DiagID) << PrevSpec;
3320    return;
3321  }
3322
3323  // If we get here, the operand to the typeof was an expresion.
3324  if (Operand.isInvalid()) {
3325    DS.SetTypeSpecError();
3326    return;
3327  }
3328
3329  const char *PrevSpec = 0;
3330  unsigned DiagID;
3331  // Check for duplicate type specifiers (e.g. "int typeof(int)").
3332  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
3333                         DiagID, Operand.release()))
3334    Diag(StartLoc, DiagID) << PrevSpec;
3335}
3336
3337
3338/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
3339/// from TryAltiVecVectorToken.
3340bool Parser::TryAltiVecVectorTokenOutOfLine() {
3341  Token Next = NextToken();
3342  switch (Next.getKind()) {
3343  default: return false;
3344  case tok::kw_short:
3345  case tok::kw_long:
3346  case tok::kw_signed:
3347  case tok::kw_unsigned:
3348  case tok::kw_void:
3349  case tok::kw_char:
3350  case tok::kw_int:
3351  case tok::kw_float:
3352  case tok::kw_double:
3353  case tok::kw_bool:
3354  case tok::kw___pixel:
3355    Tok.setKind(tok::kw___vector);
3356    return true;
3357  case tok::identifier:
3358    if (Next.getIdentifierInfo() == Ident_pixel) {
3359      Tok.setKind(tok::kw___vector);
3360      return true;
3361    }
3362    return false;
3363  }
3364}
3365
3366bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
3367                                      const char *&PrevSpec, unsigned &DiagID,
3368                                      bool &isInvalid) {
3369  if (Tok.getIdentifierInfo() == Ident_vector) {
3370    Token Next = NextToken();
3371    switch (Next.getKind()) {
3372    case tok::kw_short:
3373    case tok::kw_long:
3374    case tok::kw_signed:
3375    case tok::kw_unsigned:
3376    case tok::kw_void:
3377    case tok::kw_char:
3378    case tok::kw_int:
3379    case tok::kw_float:
3380    case tok::kw_double:
3381    case tok::kw_bool:
3382    case tok::kw___pixel:
3383      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
3384      return true;
3385    case tok::identifier:
3386      if (Next.getIdentifierInfo() == Ident_pixel) {
3387        isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
3388        return true;
3389      }
3390      break;
3391    default:
3392      break;
3393    }
3394  } else if (Tok.getIdentifierInfo() == Ident_pixel &&
3395             DS.isTypeAltiVecVector()) {
3396    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
3397    return true;
3398  }
3399  return false;
3400}
3401
3402