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