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