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