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