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