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