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