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