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