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