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