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