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