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