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