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