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