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