ParseDecl.cpp revision adcac8824a9cff13f1ef61a69e38c1041cba12ee
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/Basic/Diagnostic.h"
16#include "clang/Parse/Scope.h"
17#include "ExtensionRAIIObject.h"
18#include "AstGuard.h"
19#include "llvm/ADT/SmallSet.h"
20using namespace clang;
21
22//===----------------------------------------------------------------------===//
23// C99 6.7: Declarations.
24//===----------------------------------------------------------------------===//
25
26/// ParseTypeName
27///       type-name: [C99 6.7.6]
28///         specifier-qualifier-list abstract-declarator[opt]
29///
30/// Called type-id in C++.
31/// CXXNewMode is a special flag used by the parser of C++ new-expressions. It
32/// is simply passed on to ActOnTypeName.
33Parser::TypeTy *Parser::ParseTypeName(bool CXXNewMode) {
34  // Parse the common declaration-specifiers piece.
35  DeclSpec DS;
36  ParseSpecifierQualifierList(DS);
37
38  // Parse the abstract-declarator, if present.
39  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
40  ParseDeclarator(DeclaratorInfo);
41
42  return Actions.ActOnTypeName(CurScope, DeclaratorInfo, CXXNewMode).Val;
43}
44
45/// ParseAttributes - Parse a non-empty attributes list.
46///
47/// [GNU] attributes:
48///         attribute
49///         attributes attribute
50///
51/// [GNU]  attribute:
52///          '__attribute__' '(' '(' attribute-list ')' ')'
53///
54/// [GNU]  attribute-list:
55///          attrib
56///          attribute_list ',' attrib
57///
58/// [GNU]  attrib:
59///          empty
60///          attrib-name
61///          attrib-name '(' identifier ')'
62///          attrib-name '(' identifier ',' nonempty-expr-list ')'
63///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
64///
65/// [GNU]  attrib-name:
66///          identifier
67///          typespec
68///          typequal
69///          storageclass
70///
71/// FIXME: The GCC grammar/code for this construct implies we need two
72/// token lookahead. Comment from gcc: "If they start with an identifier
73/// which is followed by a comma or close parenthesis, then the arguments
74/// start with that identifier; otherwise they are an expression list."
75///
76/// At the moment, I am not doing 2 token lookahead. I am also unaware of
77/// any attributes that don't work (based on my limited testing). Most
78/// attributes are very simple in practice. Until we find a bug, I don't see
79/// a pressing need to implement the 2 token lookahead.
80
81AttributeList *Parser::ParseAttributes() {
82  assert(Tok.is(tok::kw___attribute) && "Not an attribute list!");
83
84  AttributeList *CurrAttr = 0;
85
86  while (Tok.is(tok::kw___attribute)) {
87    ConsumeToken();
88    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
89                         "attribute")) {
90      SkipUntil(tok::r_paren, true); // skip until ) or ;
91      return CurrAttr;
92    }
93    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
94      SkipUntil(tok::r_paren, true); // skip until ) or ;
95      return CurrAttr;
96    }
97    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
98    while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
99           Tok.is(tok::comma)) {
100
101      if (Tok.is(tok::comma)) {
102        // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
103        ConsumeToken();
104        continue;
105      }
106      // we have an identifier or declaration specifier (const, int, etc.)
107      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
108      SourceLocation AttrNameLoc = ConsumeToken();
109
110      // check if we have a "paramterized" attribute
111      if (Tok.is(tok::l_paren)) {
112        ConsumeParen(); // ignore the left paren loc for now
113
114        if (Tok.is(tok::identifier)) {
115          IdentifierInfo *ParmName = Tok.getIdentifierInfo();
116          SourceLocation ParmLoc = ConsumeToken();
117
118          if (Tok.is(tok::r_paren)) {
119            // __attribute__(( mode(byte) ))
120            ConsumeParen(); // ignore the right paren loc for now
121            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
122                                         ParmName, ParmLoc, 0, 0, CurrAttr);
123          } else if (Tok.is(tok::comma)) {
124            ConsumeToken();
125            // __attribute__(( format(printf, 1, 2) ))
126            ExprVector ArgExprs(Actions);
127            bool ArgExprsOk = true;
128
129            // now parse the non-empty comma separated list of expressions
130            while (1) {
131              ExprResult ArgExpr = ParseAssignmentExpression();
132              if (ArgExpr.isInvalid) {
133                ArgExprsOk = false;
134                SkipUntil(tok::r_paren);
135                break;
136              } else {
137                ArgExprs.push_back(ArgExpr.Val);
138              }
139              if (Tok.isNot(tok::comma))
140                break;
141              ConsumeToken(); // Eat the comma, move to the next argument
142            }
143            if (ArgExprsOk && Tok.is(tok::r_paren)) {
144              ConsumeParen(); // ignore the right paren loc for now
145              CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName,
146                           ParmLoc, ArgExprs.take(), ArgExprs.size(), CurrAttr);
147            }
148          }
149        } else { // not an identifier
150          // parse a possibly empty comma separated list of expressions
151          if (Tok.is(tok::r_paren)) {
152            // __attribute__(( nonnull() ))
153            ConsumeParen(); // ignore the right paren loc for now
154            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
155                                         0, SourceLocation(), 0, 0, CurrAttr);
156          } else {
157            // __attribute__(( aligned(16) ))
158            ExprVector ArgExprs(Actions);
159            bool ArgExprsOk = true;
160
161            // now parse the list of expressions
162            while (1) {
163              ExprResult ArgExpr = ParseAssignmentExpression();
164              if (ArgExpr.isInvalid) {
165                ArgExprsOk = false;
166                SkipUntil(tok::r_paren);
167                break;
168              } else {
169                ArgExprs.push_back(ArgExpr.Val);
170              }
171              if (Tok.isNot(tok::comma))
172                break;
173              ConsumeToken(); // Eat the comma, move to the next argument
174            }
175            // Match the ')'.
176            if (ArgExprsOk && Tok.is(tok::r_paren)) {
177              ConsumeParen(); // ignore the right paren loc for now
178              CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
179                           SourceLocation(), ArgExprs.take(), ArgExprs.size(),
180                           CurrAttr);
181            }
182          }
183        }
184      } else {
185        CurrAttr = new AttributeList(AttrName, AttrNameLoc,
186                                     0, SourceLocation(), 0, 0, CurrAttr);
187      }
188    }
189    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
190      SkipUntil(tok::r_paren, false);
191    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
192      SkipUntil(tok::r_paren, false);
193  }
194  return CurrAttr;
195}
196
197/// ParseDeclaration - Parse a full 'declaration', which consists of
198/// declaration-specifiers, some number of declarators, and a semicolon.
199/// 'Context' should be a Declarator::TheContext value.
200///
201///       declaration: [C99 6.7]
202///         block-declaration ->
203///           simple-declaration
204///           others                   [FIXME]
205/// [C++]   template-declaration
206/// [C++]   namespace-definition
207///         others... [FIXME]
208///
209Parser::DeclTy *Parser::ParseDeclaration(unsigned Context) {
210  switch (Tok.getKind()) {
211  case tok::kw_export:
212  case tok::kw_template:
213    return ParseTemplateDeclaration(Context);
214  case tok::kw_namespace:
215    return ParseNamespace(Context);
216  default:
217    return ParseSimpleDeclaration(Context);
218  }
219}
220
221///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
222///         declaration-specifiers init-declarator-list[opt] ';'
223///[C90/C++]init-declarator-list ';'                             [TODO]
224/// [OMP]   threadprivate-directive                              [TODO]
225Parser::DeclTy *Parser::ParseSimpleDeclaration(unsigned Context) {
226  // Parse the common declaration-specifiers piece.
227  DeclSpec DS;
228  ParseDeclarationSpecifiers(DS);
229
230  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
231  // declaration-specifiers init-declarator-list[opt] ';'
232  if (Tok.is(tok::semi)) {
233    ConsumeToken();
234    return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
235  }
236
237  Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
238  ParseDeclarator(DeclaratorInfo);
239
240  return ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
241}
242
243
244/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after
245/// parsing 'declaration-specifiers declarator'.  This method is split out this
246/// way to handle the ambiguity between top-level function-definitions and
247/// declarations.
248///
249///       init-declarator-list: [C99 6.7]
250///         init-declarator
251///         init-declarator-list ',' init-declarator
252///       init-declarator: [C99 6.7]
253///         declarator
254///         declarator '=' initializer
255/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
256/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
257/// [C++]   declarator initializer[opt]
258///
259/// [C++] initializer:
260/// [C++]   '=' initializer-clause
261/// [C++]   '(' expression-list ')'
262///
263Parser::DeclTy *Parser::
264ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) {
265
266  // Declarators may be grouped together ("int X, *Y, Z();").  Provide info so
267  // that they can be chained properly if the actions want this.
268  Parser::DeclTy *LastDeclInGroup = 0;
269
270  // At this point, we know that it is not a function definition.  Parse the
271  // rest of the init-declarator-list.
272  while (1) {
273    // If a simple-asm-expr is present, parse it.
274    if (Tok.is(tok::kw_asm)) {
275      ExprResult AsmLabel = ParseSimpleAsm();
276      if (AsmLabel.isInvalid) {
277        SkipUntil(tok::semi);
278        return 0;
279      }
280
281      D.setAsmLabel(AsmLabel.Val);
282    }
283
284    // If attributes are present, parse them.
285    if (Tok.is(tok::kw___attribute))
286      D.AddAttributes(ParseAttributes());
287
288    // Inform the current actions module that we just parsed this declarator.
289    LastDeclInGroup = Actions.ActOnDeclarator(CurScope, D, LastDeclInGroup);
290
291    // Parse declarator '=' initializer.
292    if (Tok.is(tok::equal)) {
293      ConsumeToken();
294      ExprResult Init = ParseInitializer();
295      if (Init.isInvalid) {
296        SkipUntil(tok::semi);
297        return 0;
298      }
299      Actions.AddInitializerToDecl(LastDeclInGroup, Init.Val);
300    } else if (Tok.is(tok::l_paren)) {
301      // Parse C++ direct initializer: '(' expression-list ')'
302      SourceLocation LParenLoc = ConsumeParen();
303      ExprVector Exprs(Actions);
304      CommaLocsTy CommaLocs;
305
306      bool InvalidExpr = false;
307      if (ParseExpressionList(Exprs, CommaLocs)) {
308        SkipUntil(tok::r_paren);
309        InvalidExpr = true;
310      }
311      // Match the ')'.
312      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
313
314      if (!InvalidExpr) {
315        assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
316               "Unexpected number of commas!");
317        Actions.AddCXXDirectInitializerToDecl(LastDeclInGroup, LParenLoc,
318                                              Exprs.take(), Exprs.size(),
319                                              &CommaLocs[0], RParenLoc);
320      }
321    } else {
322      Actions.ActOnUninitializedDecl(LastDeclInGroup);
323    }
324
325    // If we don't have a comma, it is either the end of the list (a ';') or an
326    // error, bail out.
327    if (Tok.isNot(tok::comma))
328      break;
329
330    // Consume the comma.
331    ConsumeToken();
332
333    // Parse the next declarator.
334    D.clear();
335
336    // Accept attributes in an init-declarator.  In the first declarator in a
337    // declaration, these would be part of the declspec.  In subsequent
338    // declarators, they become part of the declarator itself, so that they
339    // don't apply to declarators after *this* one.  Examples:
340    //    short __attribute__((common)) var;    -> declspec
341    //    short var __attribute__((common));    -> declarator
342    //    short x, __attribute__((common)) var;    -> declarator
343    if (Tok.is(tok::kw___attribute))
344      D.AddAttributes(ParseAttributes());
345
346    ParseDeclarator(D);
347  }
348
349  if (Tok.is(tok::semi)) {
350    ConsumeToken();
351    return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
352  }
353  // If this is an ObjC2 for-each loop, this is a successful declarator
354  // parse.  The syntax for these looks like:
355  // 'for' '(' declaration 'in' expr ')' statement
356  if (D.getContext()  == Declarator::ForContext && isTokIdentifier_in()) {
357    return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
358  }
359  Diag(Tok, diag::err_parse_error);
360  // Skip to end of block or statement
361  SkipUntil(tok::r_brace, true, true);
362  if (Tok.is(tok::semi))
363    ConsumeToken();
364  return 0;
365}
366
367/// ParseSpecifierQualifierList
368///        specifier-qualifier-list:
369///          type-specifier specifier-qualifier-list[opt]
370///          type-qualifier specifier-qualifier-list[opt]
371/// [GNU]    attributes     specifier-qualifier-list[opt]
372///
373void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
374  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
375  /// parse declaration-specifiers and complain about extra stuff.
376  ParseDeclarationSpecifiers(DS);
377
378  // Validate declspec for type-name.
379  unsigned Specs = DS.getParsedSpecifiers();
380  if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers())
381    Diag(Tok, diag::err_typename_requires_specqual);
382
383  // Issue diagnostic and remove storage class if present.
384  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
385    if (DS.getStorageClassSpecLoc().isValid())
386      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
387    else
388      Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
389    DS.ClearStorageClassSpecs();
390  }
391
392  // Issue diagnostic and remove function specfier if present.
393  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
394    if (DS.isInlineSpecified())
395      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
396    if (DS.isVirtualSpecified())
397      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
398    if (DS.isExplicitSpecified())
399      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
400    DS.ClearFunctionSpecs();
401  }
402}
403
404/// ParseDeclarationSpecifiers
405///       declaration-specifiers: [C99 6.7]
406///         storage-class-specifier declaration-specifiers[opt]
407///         type-specifier declaration-specifiers[opt]
408/// [C99]   function-specifier declaration-specifiers[opt]
409/// [GNU]   attributes declaration-specifiers[opt]
410///
411///       storage-class-specifier: [C99 6.7.1]
412///         'typedef'
413///         'extern'
414///         'static'
415///         'auto'
416///         'register'
417/// [C++]   'mutable'
418/// [GNU]   '__thread'
419///       function-specifier: [C99 6.7.4]
420/// [C99]   'inline'
421/// [C++]   'virtual'
422/// [C++]   'explicit'
423///
424void Parser::ParseDeclarationSpecifiers(DeclSpec &DS)
425{
426  DS.SetRangeStart(Tok.getLocation());
427  while (1) {
428    int isInvalid = false;
429    const char *PrevSpec = 0;
430    SourceLocation Loc = Tok.getLocation();
431
432    // Only annotate C++ scope. Allow class-name as an identifier in case
433    // it's a constructor.
434    if (getLang().CPlusPlus)
435      TryAnnotateCXXScopeToken();
436
437    switch (Tok.getKind()) {
438    default:
439      // Try to parse a type-specifier; if we found one, continue. If it's not
440      // a type, this falls through.
441      if (MaybeParseTypeSpecifier(DS, isInvalid, PrevSpec)) {
442        continue;
443      }
444
445    DoneWithDeclSpec:
446      // If this is not a declaration specifier token, we're done reading decl
447      // specifiers.  First verify that DeclSpec's are consistent.
448      DS.Finish(Diags, PP.getSourceManager(), getLang());
449      return;
450
451    case tok::annot_cxxscope: {
452      if (DS.hasTypeSpecifier())
453        goto DoneWithDeclSpec;
454
455      // We are looking for a qualified typename.
456      if (NextToken().isNot(tok::identifier))
457        goto DoneWithDeclSpec;
458
459      CXXScopeSpec SS;
460      SS.setScopeRep(Tok.getAnnotationValue());
461      SS.setRange(Tok.getAnnotationRange());
462
463      // If the next token is the name of the class type that the C++ scope
464      // denotes, followed by a '(', then this is a constructor declaration.
465      // We're done with the decl-specifiers.
466      if (Actions.isCurrentClassName(*NextToken().getIdentifierInfo(),
467                                     CurScope, &SS) &&
468          GetLookAheadToken(2).is(tok::l_paren))
469        goto DoneWithDeclSpec;
470
471      TypeTy *TypeRep = Actions.isTypeName(*NextToken().getIdentifierInfo(),
472                                           CurScope, &SS);
473      if (TypeRep == 0)
474        goto DoneWithDeclSpec;
475
476      ConsumeToken(); // The C++ scope.
477
478      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
479                                     TypeRep);
480      if (isInvalid)
481        break;
482
483      DS.SetRangeEnd(Tok.getLocation());
484      ConsumeToken(); // The typename.
485
486      continue;
487    }
488
489      // typedef-name
490    case tok::identifier: {
491      // This identifier can only be a typedef name if we haven't already seen
492      // a type-specifier.  Without this check we misparse:
493      //  typedef int X; struct Y { short X; };  as 'short int'.
494      if (DS.hasTypeSpecifier())
495        goto DoneWithDeclSpec;
496
497      // It has to be available as a typedef too!
498      TypeTy *TypeRep = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope);
499      if (TypeRep == 0)
500        goto DoneWithDeclSpec;
501
502      // C++: If the identifier is actually the name of the class type
503      // being defined and the next token is a '(', then this is a
504      // constructor declaration. We're done with the decl-specifiers
505      // and will treat this token as an identifier.
506      if (getLang().CPlusPlus &&
507          CurScope->isCXXClassScope() &&
508          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
509          NextToken().getKind() == tok::l_paren)
510        goto DoneWithDeclSpec;
511
512      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
513                                     TypeRep);
514      if (isInvalid)
515        break;
516
517      DS.SetRangeEnd(Tok.getLocation());
518      ConsumeToken(); // The identifier
519
520      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
521      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
522      // Objective-C interface.  If we don't have Objective-C or a '<', this is
523      // just a normal reference to a typedef name.
524      if (!Tok.is(tok::less) || !getLang().ObjC1)
525        continue;
526
527      SourceLocation EndProtoLoc;
528      llvm::SmallVector<DeclTy *, 8> ProtocolDecl;
529      ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
530      DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
531
532      DS.SetRangeEnd(EndProtoLoc);
533
534      // Need to support trailing type qualifiers (e.g. "id<p> const").
535      // If a type specifier follows, it will be diagnosed elsewhere.
536      continue;
537    }
538    // GNU attributes support.
539    case tok::kw___attribute:
540      DS.AddAttributes(ParseAttributes());
541      continue;
542
543    // storage-class-specifier
544    case tok::kw_typedef:
545      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec);
546      break;
547    case tok::kw_extern:
548      if (DS.isThreadSpecified())
549        Diag(Tok, diag::ext_thread_before) << "extern";
550      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec);
551      break;
552    case tok::kw___private_extern__:
553      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
554                                         PrevSpec);
555      break;
556    case tok::kw_static:
557      if (DS.isThreadSpecified())
558        Diag(Tok, diag::ext_thread_before) << "static";
559      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec);
560      break;
561    case tok::kw_auto:
562      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec);
563      break;
564    case tok::kw_register:
565      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec);
566      break;
567    case tok::kw_mutable:
568      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec);
569      break;
570    case tok::kw___thread:
571      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec)*2;
572      break;
573
574      continue;
575
576    // function-specifier
577    case tok::kw_inline:
578      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec);
579      break;
580
581    case tok::kw_virtual:
582      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec);
583      break;
584
585    case tok::kw_explicit:
586      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec);
587      break;
588
589    case tok::less:
590      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
591      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
592      // but we support it.
593      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
594        goto DoneWithDeclSpec;
595
596      {
597        SourceLocation EndProtoLoc;
598        llvm::SmallVector<DeclTy *, 8> ProtocolDecl;
599        ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
600        DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
601        DS.SetRangeEnd(EndProtoLoc);
602
603        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
604          << SourceRange(Loc, EndProtoLoc);
605        // Need to support trailing type qualifiers (e.g. "id<p> const").
606        // If a type specifier follows, it will be diagnosed elsewhere.
607        continue;
608      }
609    }
610    // If the specifier combination wasn't legal, issue a diagnostic.
611    if (isInvalid) {
612      assert(PrevSpec && "Method did not return previous specifier!");
613      // Pick between error or extwarn.
614      unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
615                                       : diag::ext_duplicate_declspec;
616      Diag(Tok, DiagID) << PrevSpec;
617    }
618    DS.SetRangeEnd(Tok.getLocation());
619    ConsumeToken();
620  }
621}
622
623/// MaybeParseTypeSpecifier - Try to parse a single type-specifier. We
624/// primarily follow the C++ grammar with additions for C99 and GNU,
625/// which together subsume the C grammar. Note that the C++
626/// type-specifier also includes the C type-qualifier (for const,
627/// volatile, and C99 restrict). Returns true if a type-specifier was
628/// found (and parsed), false otherwise.
629///
630///       type-specifier: [C++ 7.1.5]
631///         simple-type-specifier
632///         class-specifier
633///         enum-specifier
634///         elaborated-type-specifier  [TODO]
635///         cv-qualifier
636///
637///       cv-qualifier: [C++ 7.1.5.1]
638///         'const'
639///         'volatile'
640/// [C99]   'restrict'
641///
642///       simple-type-specifier: [ C++ 7.1.5.2]
643///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
644///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
645///         'char'
646///         'wchar_t'
647///         'bool'
648///         'short'
649///         'int'
650///         'long'
651///         'signed'
652///         'unsigned'
653///         'float'
654///         'double'
655///         'void'
656/// [C99]   '_Bool'
657/// [C99]   '_Complex'
658/// [C99]   '_Imaginary'  // Removed in TC2?
659/// [GNU]   '_Decimal32'
660/// [GNU]   '_Decimal64'
661/// [GNU]   '_Decimal128'
662/// [GNU]   typeof-specifier
663/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
664/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
665bool Parser::MaybeParseTypeSpecifier(DeclSpec &DS, int& isInvalid,
666                                     const char *&PrevSpec) {
667  // Annotate typenames and C++ scope specifiers.
668  TryAnnotateTypeOrScopeToken();
669
670  SourceLocation Loc = Tok.getLocation();
671
672  switch (Tok.getKind()) {
673  // simple-type-specifier:
674  case tok::annot_qualtypename: {
675    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typedef, Loc, PrevSpec,
676                                   Tok.getAnnotationValue());
677    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
678    ConsumeToken(); // The typename
679
680    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
681    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
682    // Objective-C interface.  If we don't have Objective-C or a '<', this is
683    // just a normal reference to a typedef name.
684    if (!Tok.is(tok::less) || !getLang().ObjC1)
685      return true;
686
687    SourceLocation EndProtoLoc;
688    llvm::SmallVector<DeclTy *, 8> ProtocolDecl;
689    ParseObjCProtocolReferences(ProtocolDecl, false, EndProtoLoc);
690    DS.setProtocolQualifiers(&ProtocolDecl[0], ProtocolDecl.size());
691
692    DS.SetRangeEnd(EndProtoLoc);
693    return true;
694  }
695
696  case tok::kw_short:
697    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec);
698    break;
699  case tok::kw_long:
700    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
701      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec);
702    else
703      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec);
704    break;
705  case tok::kw_signed:
706    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec);
707    break;
708  case tok::kw_unsigned:
709    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec);
710    break;
711  case tok::kw__Complex:
712    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec);
713    break;
714  case tok::kw__Imaginary:
715    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec);
716    break;
717  case tok::kw_void:
718    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec);
719    break;
720  case tok::kw_char:
721    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec);
722    break;
723  case tok::kw_int:
724    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec);
725    break;
726  case tok::kw_float:
727    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec);
728    break;
729  case tok::kw_double:
730    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec);
731    break;
732  case tok::kw_wchar_t:
733    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec);
734    break;
735  case tok::kw_bool:
736  case tok::kw__Bool:
737    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec);
738    break;
739  case tok::kw__Decimal32:
740    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec);
741    break;
742  case tok::kw__Decimal64:
743    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec);
744    break;
745  case tok::kw__Decimal128:
746    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec);
747    break;
748
749  // class-specifier:
750  case tok::kw_class:
751  case tok::kw_struct:
752  case tok::kw_union:
753    ParseClassSpecifier(DS);
754    return true;
755
756  // enum-specifier:
757  case tok::kw_enum:
758    ParseEnumSpecifier(DS);
759    return true;
760
761  // cv-qualifier:
762  case tok::kw_const:
763    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
764                               getLang())*2;
765    break;
766  case tok::kw_volatile:
767    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
768                               getLang())*2;
769    break;
770  case tok::kw_restrict:
771    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
772                               getLang())*2;
773    break;
774
775  // GNU typeof support.
776  case tok::kw_typeof:
777    ParseTypeofSpecifier(DS);
778    return true;
779
780  default:
781    // Not a type-specifier; do nothing.
782    return false;
783  }
784
785  // If the specifier combination wasn't legal, issue a diagnostic.
786  if (isInvalid) {
787    assert(PrevSpec && "Method did not return previous specifier!");
788    // Pick between error or extwarn.
789    unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
790                                     : diag::ext_duplicate_declspec;
791    Diag(Tok, DiagID) << PrevSpec;
792  }
793  DS.SetRangeEnd(Tok.getLocation());
794  ConsumeToken(); // whatever we parsed above.
795  return true;
796}
797
798/// ParseStructDeclaration - Parse a struct declaration without the terminating
799/// semicolon.
800///
801///       struct-declaration:
802///         specifier-qualifier-list struct-declarator-list
803/// [GNU]   __extension__ struct-declaration
804/// [GNU]   specifier-qualifier-list
805///       struct-declarator-list:
806///         struct-declarator
807///         struct-declarator-list ',' struct-declarator
808/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
809///       struct-declarator:
810///         declarator
811/// [GNU]   declarator attributes[opt]
812///         declarator[opt] ':' constant-expression
813/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
814///
815void Parser::
816ParseStructDeclaration(DeclSpec &DS,
817                       llvm::SmallVectorImpl<FieldDeclarator> &Fields) {
818  if (Tok.is(tok::kw___extension__)) {
819    // __extension__ silences extension warnings in the subexpression.
820    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
821    ConsumeToken();
822    return ParseStructDeclaration(DS, Fields);
823  }
824
825  // Parse the common specifier-qualifiers-list piece.
826  SourceLocation DSStart = Tok.getLocation();
827  ParseSpecifierQualifierList(DS);
828
829  // If there are no declarators, issue a warning.
830  if (Tok.is(tok::semi)) {
831    Diag(DSStart, diag::w_no_declarators);
832    return;
833  }
834
835  // Read struct-declarators until we find the semicolon.
836  Fields.push_back(FieldDeclarator(DS));
837  while (1) {
838    FieldDeclarator &DeclaratorInfo = Fields.back();
839
840    /// struct-declarator: declarator
841    /// struct-declarator: declarator[opt] ':' constant-expression
842    if (Tok.isNot(tok::colon))
843      ParseDeclarator(DeclaratorInfo.D);
844
845    if (Tok.is(tok::colon)) {
846      ConsumeToken();
847      ExprResult Res = ParseConstantExpression();
848      if (Res.isInvalid)
849        SkipUntil(tok::semi, true, true);
850      else
851        DeclaratorInfo.BitfieldSize = Res.Val;
852    }
853
854    // If attributes exist after the declarator, parse them.
855    if (Tok.is(tok::kw___attribute))
856      DeclaratorInfo.D.AddAttributes(ParseAttributes());
857
858    // If we don't have a comma, it is either the end of the list (a ';')
859    // or an error, bail out.
860    if (Tok.isNot(tok::comma))
861      return;
862
863    // Consume the comma.
864    ConsumeToken();
865
866    // Parse the next declarator.
867    Fields.push_back(FieldDeclarator(DS));
868
869    // Attributes are only allowed on the second declarator.
870    if (Tok.is(tok::kw___attribute))
871      Fields.back().D.AddAttributes(ParseAttributes());
872  }
873}
874
875/// ParseStructUnionBody
876///       struct-contents:
877///         struct-declaration-list
878/// [EXT]   empty
879/// [GNU]   "struct-declaration-list" without terminatoring ';'
880///       struct-declaration-list:
881///         struct-declaration
882///         struct-declaration-list struct-declaration
883/// [OBC]   '@' 'defs' '(' class-name ')'
884///
885void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
886                                  unsigned TagType, DeclTy *TagDecl) {
887  SourceLocation LBraceLoc = ConsumeBrace();
888
889  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
890  // C++.
891  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
892    Diag(Tok, diag::ext_empty_struct_union_enum)
893      << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
894
895  llvm::SmallVector<DeclTy*, 32> FieldDecls;
896  llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators;
897
898  // While we still have something to read, read the declarations in the struct.
899  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
900    // Each iteration of this loop reads one struct-declaration.
901
902    // Check for extraneous top-level semicolon.
903    if (Tok.is(tok::semi)) {
904      Diag(Tok, diag::ext_extra_struct_semi);
905      ConsumeToken();
906      continue;
907    }
908
909    // Parse all the comma separated declarators.
910    DeclSpec DS;
911    FieldDeclarators.clear();
912    if (!Tok.is(tok::at)) {
913      ParseStructDeclaration(DS, FieldDeclarators);
914
915      // Convert them all to fields.
916      for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) {
917        FieldDeclarator &FD = FieldDeclarators[i];
918        // Install the declarator into the current TagDecl.
919        DeclTy *Field = Actions.ActOnField(CurScope,
920                                           DS.getSourceRange().getBegin(),
921                                           FD.D, FD.BitfieldSize);
922        FieldDecls.push_back(Field);
923      }
924    } else { // Handle @defs
925      ConsumeToken();
926      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
927        Diag(Tok, diag::err_unexpected_at);
928        SkipUntil(tok::semi, true, true);
929        continue;
930      }
931      ConsumeToken();
932      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
933      if (!Tok.is(tok::identifier)) {
934        Diag(Tok, diag::err_expected_ident);
935        SkipUntil(tok::semi, true, true);
936        continue;
937      }
938      llvm::SmallVector<DeclTy*, 16> Fields;
939      Actions.ActOnDefs(CurScope, Tok.getLocation(), Tok.getIdentifierInfo(),
940          Fields);
941      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
942      ConsumeToken();
943      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
944    }
945
946    if (Tok.is(tok::semi)) {
947      ConsumeToken();
948    } else if (Tok.is(tok::r_brace)) {
949      Diag(Tok, diag::ext_expected_semi_decl_list);
950      break;
951    } else {
952      Diag(Tok, diag::err_expected_semi_decl_list);
953      // Skip to end of block or statement
954      SkipUntil(tok::r_brace, true, true);
955    }
956  }
957
958  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
959
960  AttributeList *AttrList = 0;
961  // If attributes exist after struct contents, parse them.
962  if (Tok.is(tok::kw___attribute))
963    AttrList = ParseAttributes();
964
965  Actions.ActOnFields(CurScope,
966                      RecordLoc,TagDecl,&FieldDecls[0],FieldDecls.size(),
967                      LBraceLoc, RBraceLoc,
968                      AttrList);
969}
970
971
972/// ParseEnumSpecifier
973///       enum-specifier: [C99 6.7.2.2]
974///         'enum' identifier[opt] '{' enumerator-list '}'
975///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
976/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
977///                                                 '}' attributes[opt]
978///         'enum' identifier
979/// [GNU]   'enum' attributes[opt] identifier
980///
981/// [C++] elaborated-type-specifier:
982/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
983///
984void Parser::ParseEnumSpecifier(DeclSpec &DS) {
985  assert(Tok.is(tok::kw_enum) && "Not an enum specifier");
986  SourceLocation StartLoc = ConsumeToken();
987
988  // Parse the tag portion of this.
989
990  AttributeList *Attr = 0;
991  // If attributes exist after tag, parse them.
992  if (Tok.is(tok::kw___attribute))
993    Attr = ParseAttributes();
994
995  CXXScopeSpec SS;
996  if (getLang().CPlusPlus && MaybeParseCXXScopeSpecifier(SS)) {
997    if (Tok.isNot(tok::identifier)) {
998      Diag(Tok, diag::err_expected_ident);
999      if (Tok.isNot(tok::l_brace)) {
1000        // Has no name and is not a definition.
1001        // Skip the rest of this declarator, up until the comma or semicolon.
1002        SkipUntil(tok::comma, true);
1003        return;
1004      }
1005    }
1006  }
1007
1008  // Must have either 'enum name' or 'enum {...}'.
1009  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1010    Diag(Tok, diag::err_expected_ident_lbrace);
1011
1012    // Skip the rest of this declarator, up until the comma or semicolon.
1013    SkipUntil(tok::comma, true);
1014    return;
1015  }
1016
1017  // If an identifier is present, consume and remember it.
1018  IdentifierInfo *Name = 0;
1019  SourceLocation NameLoc;
1020  if (Tok.is(tok::identifier)) {
1021    Name = Tok.getIdentifierInfo();
1022    NameLoc = ConsumeToken();
1023  }
1024
1025  // There are three options here.  If we have 'enum foo;', then this is a
1026  // forward declaration.  If we have 'enum foo {...' then this is a
1027  // definition. Otherwise we have something like 'enum foo xyz', a reference.
1028  //
1029  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1030  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
1031  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
1032  //
1033  Action::TagKind TK;
1034  if (Tok.is(tok::l_brace))
1035    TK = Action::TK_Definition;
1036  else if (Tok.is(tok::semi))
1037    TK = Action::TK_Declaration;
1038  else
1039    TK = Action::TK_Reference;
1040  DeclTy *TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TK, StartLoc,
1041                                     SS, Name, NameLoc, Attr);
1042
1043  if (Tok.is(tok::l_brace))
1044    ParseEnumBody(StartLoc, TagDecl);
1045
1046  // TODO: semantic analysis on the declspec for enums.
1047  const char *PrevSpec = 0;
1048  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, TagDecl))
1049    Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
1050}
1051
1052/// ParseEnumBody - Parse a {} enclosed enumerator-list.
1053///       enumerator-list:
1054///         enumerator
1055///         enumerator-list ',' enumerator
1056///       enumerator:
1057///         enumeration-constant
1058///         enumeration-constant '=' constant-expression
1059///       enumeration-constant:
1060///         identifier
1061///
1062void Parser::ParseEnumBody(SourceLocation StartLoc, DeclTy *EnumDecl) {
1063  SourceLocation LBraceLoc = ConsumeBrace();
1064
1065  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
1066  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1067    Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
1068
1069  llvm::SmallVector<DeclTy*, 32> EnumConstantDecls;
1070
1071  DeclTy *LastEnumConstDecl = 0;
1072
1073  // Parse the enumerator-list.
1074  while (Tok.is(tok::identifier)) {
1075    IdentifierInfo *Ident = Tok.getIdentifierInfo();
1076    SourceLocation IdentLoc = ConsumeToken();
1077
1078    SourceLocation EqualLoc;
1079    ExprTy *AssignedVal = 0;
1080    if (Tok.is(tok::equal)) {
1081      EqualLoc = ConsumeToken();
1082      ExprResult Res = ParseConstantExpression();
1083      if (Res.isInvalid)
1084        SkipUntil(tok::comma, tok::r_brace, true, true);
1085      else
1086        AssignedVal = Res.Val;
1087    }
1088
1089    // Install the enumerator constant into EnumDecl.
1090    DeclTy *EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1091                                                      LastEnumConstDecl,
1092                                                      IdentLoc, Ident,
1093                                                      EqualLoc, AssignedVal);
1094    EnumConstantDecls.push_back(EnumConstDecl);
1095    LastEnumConstDecl = EnumConstDecl;
1096
1097    if (Tok.isNot(tok::comma))
1098      break;
1099    SourceLocation CommaLoc = ConsumeToken();
1100
1101    if (Tok.isNot(tok::identifier) && !getLang().C99)
1102      Diag(CommaLoc, diag::ext_c99_enumerator_list_comma);
1103  }
1104
1105  // Eat the }.
1106  MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1107
1108  Actions.ActOnEnumBody(StartLoc, EnumDecl, &EnumConstantDecls[0],
1109                        EnumConstantDecls.size());
1110
1111  DeclTy *AttrList = 0;
1112  // If attributes exist after the identifier list, parse them.
1113  if (Tok.is(tok::kw___attribute))
1114    AttrList = ParseAttributes(); // FIXME: where do they do?
1115}
1116
1117/// isTypeSpecifierQualifier - Return true if the current token could be the
1118/// start of a type-qualifier-list.
1119bool Parser::isTypeQualifier() const {
1120  switch (Tok.getKind()) {
1121  default: return false;
1122    // type-qualifier
1123  case tok::kw_const:
1124  case tok::kw_volatile:
1125  case tok::kw_restrict:
1126    return true;
1127  }
1128}
1129
1130/// isTypeSpecifierQualifier - Return true if the current token could be the
1131/// start of a specifier-qualifier-list.
1132bool Parser::isTypeSpecifierQualifier() {
1133  // Annotate typenames and C++ scope specifiers.
1134  TryAnnotateTypeOrScopeToken();
1135
1136  switch (Tok.getKind()) {
1137  default: return false;
1138    // GNU attributes support.
1139  case tok::kw___attribute:
1140    // GNU typeof support.
1141  case tok::kw_typeof:
1142
1143    // type-specifiers
1144  case tok::kw_short:
1145  case tok::kw_long:
1146  case tok::kw_signed:
1147  case tok::kw_unsigned:
1148  case tok::kw__Complex:
1149  case tok::kw__Imaginary:
1150  case tok::kw_void:
1151  case tok::kw_char:
1152  case tok::kw_wchar_t:
1153  case tok::kw_int:
1154  case tok::kw_float:
1155  case tok::kw_double:
1156  case tok::kw_bool:
1157  case tok::kw__Bool:
1158  case tok::kw__Decimal32:
1159  case tok::kw__Decimal64:
1160  case tok::kw__Decimal128:
1161
1162    // struct-or-union-specifier (C99) or class-specifier (C++)
1163  case tok::kw_class:
1164  case tok::kw_struct:
1165  case tok::kw_union:
1166    // enum-specifier
1167  case tok::kw_enum:
1168
1169    // type-qualifier
1170  case tok::kw_const:
1171  case tok::kw_volatile:
1172  case tok::kw_restrict:
1173
1174    // typedef-name
1175  case tok::annot_qualtypename:
1176    return true;
1177
1178    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1179  case tok::less:
1180    return getLang().ObjC1;
1181  }
1182}
1183
1184/// isDeclarationSpecifier() - Return true if the current token is part of a
1185/// declaration specifier.
1186bool Parser::isDeclarationSpecifier() {
1187  // Annotate typenames and C++ scope specifiers.
1188  TryAnnotateTypeOrScopeToken();
1189
1190  switch (Tok.getKind()) {
1191  default: return false;
1192    // storage-class-specifier
1193  case tok::kw_typedef:
1194  case tok::kw_extern:
1195  case tok::kw___private_extern__:
1196  case tok::kw_static:
1197  case tok::kw_auto:
1198  case tok::kw_register:
1199  case tok::kw___thread:
1200
1201    // type-specifiers
1202  case tok::kw_short:
1203  case tok::kw_long:
1204  case tok::kw_signed:
1205  case tok::kw_unsigned:
1206  case tok::kw__Complex:
1207  case tok::kw__Imaginary:
1208  case tok::kw_void:
1209  case tok::kw_char:
1210  case tok::kw_wchar_t:
1211  case tok::kw_int:
1212  case tok::kw_float:
1213  case tok::kw_double:
1214  case tok::kw_bool:
1215  case tok::kw__Bool:
1216  case tok::kw__Decimal32:
1217  case tok::kw__Decimal64:
1218  case tok::kw__Decimal128:
1219
1220    // struct-or-union-specifier (C99) or class-specifier (C++)
1221  case tok::kw_class:
1222  case tok::kw_struct:
1223  case tok::kw_union:
1224    // enum-specifier
1225  case tok::kw_enum:
1226
1227    // type-qualifier
1228  case tok::kw_const:
1229  case tok::kw_volatile:
1230  case tok::kw_restrict:
1231
1232    // function-specifier
1233  case tok::kw_inline:
1234  case tok::kw_virtual:
1235  case tok::kw_explicit:
1236
1237    // typedef-name
1238  case tok::annot_qualtypename:
1239
1240    // GNU typeof support.
1241  case tok::kw_typeof:
1242
1243    // GNU attributes.
1244  case tok::kw___attribute:
1245    return true;
1246
1247    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1248  case tok::less:
1249    return getLang().ObjC1;
1250  }
1251}
1252
1253
1254/// ParseTypeQualifierListOpt
1255///       type-qualifier-list: [C99 6.7.5]
1256///         type-qualifier
1257/// [GNU]   attributes
1258///         type-qualifier-list type-qualifier
1259/// [GNU]   type-qualifier-list attributes
1260///
1261void Parser::ParseTypeQualifierListOpt(DeclSpec &DS) {
1262  while (1) {
1263    int isInvalid = false;
1264    const char *PrevSpec = 0;
1265    SourceLocation Loc = Tok.getLocation();
1266
1267    switch (Tok.getKind()) {
1268    default:
1269      // If this is not a type-qualifier token, we're done reading type
1270      // qualifiers.  First verify that DeclSpec's are consistent.
1271      DS.Finish(Diags, PP.getSourceManager(), getLang());
1272      return;
1273    case tok::kw_const:
1274      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1275                                 getLang())*2;
1276      break;
1277    case tok::kw_volatile:
1278      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1279                                 getLang())*2;
1280      break;
1281    case tok::kw_restrict:
1282      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1283                                 getLang())*2;
1284      break;
1285    case tok::kw___attribute:
1286      DS.AddAttributes(ParseAttributes());
1287      continue; // do *not* consume the next token!
1288    }
1289
1290    // If the specifier combination wasn't legal, issue a diagnostic.
1291    if (isInvalid) {
1292      assert(PrevSpec && "Method did not return previous specifier!");
1293      // Pick between error or extwarn.
1294      unsigned DiagID = isInvalid == 1 ? diag::err_invalid_decl_spec_combination
1295                                      : diag::ext_duplicate_declspec;
1296      Diag(Tok, DiagID) << PrevSpec;
1297    }
1298    ConsumeToken();
1299  }
1300}
1301
1302
1303/// ParseDeclarator - Parse and verify a newly-initialized declarator.
1304///
1305void Parser::ParseDeclarator(Declarator &D) {
1306  /// This implements the 'declarator' production in the C grammar, then checks
1307  /// for well-formedness and issues diagnostics.
1308  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
1309}
1310
1311/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
1312/// is parsed by the function passed to it. Pass null, and the direct-declarator
1313/// isn't parsed at all, making this function effectively parse the C++
1314/// ptr-operator production.
1315///
1316///       declarator: [C99 6.7.5]
1317///         pointer[opt] direct-declarator
1318/// [C++]   '&' declarator [C++ 8p4, dcl.decl]
1319/// [GNU]   '&' restrict[opt] attributes[opt] declarator
1320///
1321///       pointer: [C99 6.7.5]
1322///         '*' type-qualifier-list[opt]
1323///         '*' type-qualifier-list[opt] pointer
1324///
1325///       ptr-operator:
1326///         '*' cv-qualifier-seq[opt]
1327///         '&'
1328/// [GNU]   '&' restrict[opt] attributes[opt]
1329///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] [TODO]
1330void Parser::ParseDeclaratorInternal(Declarator &D,
1331                                     DirectDeclParseFunction DirectDeclParser) {
1332  tok::TokenKind Kind = Tok.getKind();
1333
1334  // Not a pointer, C++ reference, or block.
1335  if (Kind != tok::star && (Kind != tok::amp || !getLang().CPlusPlus) &&
1336      (Kind != tok::caret || !getLang().Blocks)) {
1337    if (DirectDeclParser)
1338      (this->*DirectDeclParser)(D);
1339    return;
1340  }
1341
1342  // Otherwise, '*' -> pointer, '^' -> block, '&' -> reference.
1343  SourceLocation Loc = ConsumeToken();  // Eat the * or &.
1344
1345  if (Kind == tok::star || (Kind == tok::caret && getLang().Blocks)) {
1346    // Is a pointer.
1347    DeclSpec DS;
1348
1349    ParseTypeQualifierListOpt(DS);
1350
1351    // Recursively parse the declarator.
1352    ParseDeclaratorInternal(D, DirectDeclParser);
1353    if (Kind == tok::star)
1354      // Remember that we parsed a pointer type, and remember the type-quals.
1355      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
1356                                                DS.TakeAttributes()));
1357    else
1358      // Remember that we parsed a Block type, and remember the type-quals.
1359      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
1360                                                     Loc));
1361  } else {
1362    // Is a reference
1363    DeclSpec DS;
1364
1365    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
1366    // cv-qualifiers are introduced through the use of a typedef or of a
1367    // template type argument, in which case the cv-qualifiers are ignored.
1368    //
1369    // [GNU] Retricted references are allowed.
1370    // [GNU] Attributes on references are allowed.
1371    ParseTypeQualifierListOpt(DS);
1372
1373    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
1374      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
1375        Diag(DS.getConstSpecLoc(),
1376             diag::err_invalid_reference_qualifier_application) << "const";
1377      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
1378        Diag(DS.getVolatileSpecLoc(),
1379             diag::err_invalid_reference_qualifier_application) << "volatile";
1380    }
1381
1382    // Recursively parse the declarator.
1383    ParseDeclaratorInternal(D, DirectDeclParser);
1384
1385    if (D.getNumTypeObjects() > 0) {
1386      // C++ [dcl.ref]p4: There shall be no references to references.
1387      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
1388      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
1389        if (const IdentifierInfo *II = D.getIdentifier())
1390          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
1391           << II;
1392        else
1393          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
1394            << "type name";
1395
1396        // Once we've complained about the reference-to-reference, we
1397        // can go ahead and build the (technically ill-formed)
1398        // declarator: reference collapsing will take care of it.
1399      }
1400    }
1401
1402    // Remember that we parsed a reference type. It doesn't have type-quals.
1403    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
1404                                                DS.TakeAttributes()));
1405  }
1406}
1407
1408/// ParseDirectDeclarator
1409///       direct-declarator: [C99 6.7.5]
1410/// [C99]   identifier
1411///         '(' declarator ')'
1412/// [GNU]   '(' attributes declarator ')'
1413/// [C90]   direct-declarator '[' constant-expression[opt] ']'
1414/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1415/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1416/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1417/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
1418///         direct-declarator '(' parameter-type-list ')'
1419///         direct-declarator '(' identifier-list[opt] ')'
1420/// [GNU]   direct-declarator '(' parameter-forward-declarations
1421///                    parameter-type-list[opt] ')'
1422/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
1423///                    cv-qualifier-seq[opt] exception-specification[opt]
1424/// [C++]   declarator-id
1425///
1426///       declarator-id: [C++ 8]
1427///         id-expression
1428///         '::'[opt] nested-name-specifier[opt] type-name
1429///
1430///       id-expression: [C++ 5.1]
1431///         unqualified-id
1432///         qualified-id            [TODO]
1433///
1434///       unqualified-id: [C++ 5.1]
1435///         identifier
1436///         operator-function-id
1437///         conversion-function-id  [TODO]
1438///          '~' class-name
1439///         template-id             [TODO]
1440///
1441void Parser::ParseDirectDeclarator(Declarator &D) {
1442  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
1443
1444  if (getLang().CPlusPlus) {
1445    if (D.mayHaveIdentifier()) {
1446      bool afterCXXScope = MaybeParseCXXScopeSpecifier(D.getCXXScopeSpec());
1447      if (afterCXXScope) {
1448        // Change the declaration context for name lookup, until this function
1449        // is exited (and the declarator has been parsed).
1450        DeclScopeObj.EnterDeclaratorScope();
1451      }
1452
1453      if (Tok.is(tok::identifier)) {
1454        assert(Tok.getIdentifierInfo() && "Not an identifier?");
1455        // Determine whether this identifier is a C++ constructor name or
1456        // a normal identifier.
1457        if (Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope)) {
1458          D.setConstructor(Actions.isTypeName(*Tok.getIdentifierInfo(),
1459                                              CurScope),
1460                           Tok.getLocation());
1461        } else
1462          D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1463        ConsumeToken();
1464        goto PastIdentifier;
1465      }
1466
1467      if (Tok.is(tok::tilde)) {
1468        // This should be a C++ destructor.
1469        SourceLocation TildeLoc = ConsumeToken();
1470        if (Tok.is(tok::identifier)) {
1471          if (TypeTy *Type = ParseClassName())
1472            D.setDestructor(Type, TildeLoc);
1473          else
1474            D.SetIdentifier(0, TildeLoc);
1475        } else {
1476          Diag(Tok, diag::err_expected_class_name);
1477          D.SetIdentifier(0, TildeLoc);
1478        }
1479        goto PastIdentifier;
1480      }
1481
1482      // If we reached this point, token is not identifier and not '~'.
1483
1484      if (afterCXXScope) {
1485        Diag(Tok, diag::err_expected_unqualified_id);
1486        D.SetIdentifier(0, Tok.getLocation());
1487        D.setInvalidType(true);
1488        goto PastIdentifier;
1489      }
1490    }
1491
1492    if (Tok.is(tok::kw_operator)) {
1493      SourceLocation OperatorLoc = Tok.getLocation();
1494
1495      // First try the name of an overloaded operator
1496      if (OverloadedOperatorKind Op = TryParseOperatorFunctionId()) {
1497        D.setOverloadedOperator(Op, OperatorLoc);
1498      } else {
1499        // This must be a conversion function (C++ [class.conv.fct]).
1500        if (TypeTy *ConvType = ParseConversionFunctionId())
1501          D.setConversionFunction(ConvType, OperatorLoc);
1502        else
1503          D.SetIdentifier(0, Tok.getLocation());
1504      }
1505      goto PastIdentifier;
1506    }
1507  }
1508
1509  // If we reached this point, we are either in C/ObjC or the token didn't
1510  // satisfy any of the C++-specific checks.
1511
1512  if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
1513    assert(!getLang().CPlusPlus &&
1514           "There's a C++-specific check for tok::identifier above");
1515    assert(Tok.getIdentifierInfo() && "Not an identifier?");
1516    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1517    ConsumeToken();
1518  } else if (Tok.is(tok::l_paren)) {
1519    // direct-declarator: '(' declarator ')'
1520    // direct-declarator: '(' attributes declarator ')'
1521    // Example: 'char (*X)'   or 'int (*XX)(void)'
1522    ParseParenDeclarator(D);
1523  } else if (D.mayOmitIdentifier()) {
1524    // This could be something simple like "int" (in which case the declarator
1525    // portion is empty), if an abstract-declarator is allowed.
1526    D.SetIdentifier(0, Tok.getLocation());
1527  } else {
1528    if (getLang().CPlusPlus)
1529      Diag(Tok, diag::err_expected_unqualified_id);
1530    else
1531      Diag(Tok, diag::err_expected_ident_lparen);
1532    D.SetIdentifier(0, Tok.getLocation());
1533    D.setInvalidType(true);
1534  }
1535
1536 PastIdentifier:
1537  assert(D.isPastIdentifier() &&
1538         "Haven't past the location of the identifier yet?");
1539
1540  while (1) {
1541    if (Tok.is(tok::l_paren)) {
1542      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
1543      // In such a case, check if we actually have a function declarator; if it
1544      // is not, the declarator has been fully parsed.
1545      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
1546        // When not in file scope, warn for ambiguous function declarators, just
1547        // in case the author intended it as a variable definition.
1548        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
1549        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
1550          break;
1551      }
1552      ParseFunctionDeclarator(ConsumeParen(), D);
1553    } else if (Tok.is(tok::l_square)) {
1554      ParseBracketDeclarator(D);
1555    } else {
1556      break;
1557    }
1558  }
1559}
1560
1561/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
1562/// only called before the identifier, so these are most likely just grouping
1563/// parens for precedence.  If we find that these are actually function
1564/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
1565///
1566///       direct-declarator:
1567///         '(' declarator ')'
1568/// [GNU]   '(' attributes declarator ')'
1569///         direct-declarator '(' parameter-type-list ')'
1570///         direct-declarator '(' identifier-list[opt] ')'
1571/// [GNU]   direct-declarator '(' parameter-forward-declarations
1572///                    parameter-type-list[opt] ')'
1573///
1574void Parser::ParseParenDeclarator(Declarator &D) {
1575  SourceLocation StartLoc = ConsumeParen();
1576  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
1577
1578  // Eat any attributes before we look at whether this is a grouping or function
1579  // declarator paren.  If this is a grouping paren, the attribute applies to
1580  // the type being built up, for example:
1581  //     int (__attribute__(()) *x)(long y)
1582  // If this ends up not being a grouping paren, the attribute applies to the
1583  // first argument, for example:
1584  //     int (__attribute__(()) int x)
1585  // In either case, we need to eat any attributes to be able to determine what
1586  // sort of paren this is.
1587  //
1588  AttributeList *AttrList = 0;
1589  bool RequiresArg = false;
1590  if (Tok.is(tok::kw___attribute)) {
1591    AttrList = ParseAttributes();
1592
1593    // We require that the argument list (if this is a non-grouping paren) be
1594    // present even if the attribute list was empty.
1595    RequiresArg = true;
1596  }
1597
1598  // If we haven't past the identifier yet (or where the identifier would be
1599  // stored, if this is an abstract declarator), then this is probably just
1600  // grouping parens. However, if this could be an abstract-declarator, then
1601  // this could also be the start of function arguments (consider 'void()').
1602  bool isGrouping;
1603
1604  if (!D.mayOmitIdentifier()) {
1605    // If this can't be an abstract-declarator, this *must* be a grouping
1606    // paren, because we haven't seen the identifier yet.
1607    isGrouping = true;
1608  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
1609             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
1610             isDeclarationSpecifier()) {       // 'int(int)' is a function.
1611    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
1612    // considered to be a type, not a K&R identifier-list.
1613    isGrouping = false;
1614  } else {
1615    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
1616    isGrouping = true;
1617  }
1618
1619  // If this is a grouping paren, handle:
1620  // direct-declarator: '(' declarator ')'
1621  // direct-declarator: '(' attributes declarator ')'
1622  if (isGrouping) {
1623    bool hadGroupingParens = D.hasGroupingParens();
1624    D.setGroupingParens(true);
1625    if (AttrList)
1626      D.AddAttributes(AttrList);
1627
1628    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
1629    // Match the ')'.
1630    MatchRHSPunctuation(tok::r_paren, StartLoc);
1631
1632    D.setGroupingParens(hadGroupingParens);
1633    return;
1634  }
1635
1636  // Okay, if this wasn't a grouping paren, it must be the start of a function
1637  // argument list.  Recognize that this declarator will never have an
1638  // identifier (and remember where it would have been), then call into
1639  // ParseFunctionDeclarator to handle of argument list.
1640  D.SetIdentifier(0, Tok.getLocation());
1641
1642  ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg);
1643}
1644
1645/// ParseFunctionDeclarator - We are after the identifier and have parsed the
1646/// declarator D up to a paren, which indicates that we are parsing function
1647/// arguments.
1648///
1649/// If AttrList is non-null, then the caller parsed those arguments immediately
1650/// after the open paren - they should be considered to be the first argument of
1651/// a parameter.  If RequiresArg is true, then the first argument of the
1652/// function is required to be present and required to not be an identifier
1653/// list.
1654///
1655/// This method also handles this portion of the grammar:
1656///       parameter-type-list: [C99 6.7.5]
1657///         parameter-list
1658///         parameter-list ',' '...'
1659///
1660///       parameter-list: [C99 6.7.5]
1661///         parameter-declaration
1662///         parameter-list ',' parameter-declaration
1663///
1664///       parameter-declaration: [C99 6.7.5]
1665///         declaration-specifiers declarator
1666/// [C++]   declaration-specifiers declarator '=' assignment-expression
1667/// [GNU]   declaration-specifiers declarator attributes
1668///         declaration-specifiers abstract-declarator[opt]
1669/// [C++]   declaration-specifiers abstract-declarator[opt]
1670///           '=' assignment-expression
1671/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
1672///
1673/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
1674/// and "exception-specification[opt]"(TODO).
1675///
1676void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
1677                                     AttributeList *AttrList,
1678                                     bool RequiresArg) {
1679  // lparen is already consumed!
1680  assert(D.isPastIdentifier() && "Should not call before identifier!");
1681
1682  // This parameter list may be empty.
1683  if (Tok.is(tok::r_paren)) {
1684    if (RequiresArg) {
1685      Diag(Tok, diag::err_argument_required_after_attribute);
1686      delete AttrList;
1687    }
1688
1689    ConsumeParen();  // Eat the closing ')'.
1690
1691    // cv-qualifier-seq[opt].
1692    DeclSpec DS;
1693    if (getLang().CPlusPlus) {
1694      ParseTypeQualifierListOpt(DS);
1695
1696      // Parse exception-specification[opt].
1697      if (Tok.is(tok::kw_throw))
1698        ParseExceptionSpecification();
1699    }
1700
1701    // Remember that we parsed a function type, and remember the attributes.
1702    // int() -> no prototype, no '...'.
1703    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
1704                                               /*variadic*/ false,
1705                                               /*arglist*/ 0, 0,
1706                                               DS.getTypeQualifiers(),
1707                                               LParenLoc));
1708    return;
1709  }
1710
1711  // Alternatively, this parameter list may be an identifier list form for a
1712  // K&R-style function:  void foo(a,b,c)
1713  if (!getLang().CPlusPlus && Tok.is(tok::identifier) &&
1714      // K&R identifier lists can't have typedefs as identifiers, per
1715      // C99 6.7.5.3p11.
1716      !Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
1717    if (RequiresArg) {
1718      Diag(Tok, diag::err_argument_required_after_attribute);
1719      delete AttrList;
1720    }
1721
1722    // Identifier list.  Note that '(' identifier-list ')' is only allowed for
1723    // normal declarators, not for abstract-declarators.
1724    return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
1725  }
1726
1727  // Finally, a normal, non-empty parameter type list.
1728
1729  // Build up an array of information about the parsed arguments.
1730  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1731
1732  // Enter function-declaration scope, limiting any declarators to the
1733  // function prototype scope, including parameter declarators.
1734  EnterScope(Scope::FnScope|Scope::DeclScope);
1735
1736  bool IsVariadic = false;
1737  while (1) {
1738    if (Tok.is(tok::ellipsis)) {
1739      IsVariadic = true;
1740
1741      // Check to see if this is "void(...)" which is not allowed.
1742      if (!getLang().CPlusPlus && ParamInfo.empty()) {
1743        // Otherwise, parse parameter type list.  If it starts with an
1744        // ellipsis,  diagnose the malformed function.
1745        Diag(Tok, diag::err_ellipsis_first_arg);
1746        IsVariadic = false;       // Treat this like 'void()'.
1747      }
1748
1749      ConsumeToken();     // Consume the ellipsis.
1750      break;
1751    }
1752
1753    SourceLocation DSStart = Tok.getLocation();
1754
1755    // Parse the declaration-specifiers.
1756    DeclSpec DS;
1757
1758    // If the caller parsed attributes for the first argument, add them now.
1759    if (AttrList) {
1760      DS.AddAttributes(AttrList);
1761      AttrList = 0;  // Only apply the attributes to the first parameter.
1762    }
1763    ParseDeclarationSpecifiers(DS);
1764
1765    // Parse the declarator.  This is "PrototypeContext", because we must
1766    // accept either 'declarator' or 'abstract-declarator' here.
1767    Declarator ParmDecl(DS, Declarator::PrototypeContext);
1768    ParseDeclarator(ParmDecl);
1769
1770    // Parse GNU attributes, if present.
1771    if (Tok.is(tok::kw___attribute))
1772      ParmDecl.AddAttributes(ParseAttributes());
1773
1774    // Remember this parsed parameter in ParamInfo.
1775    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1776
1777    // If no parameter was specified, verify that *something* was specified,
1778    // otherwise we have a missing type and identifier.
1779    if (DS.getParsedSpecifiers() == DeclSpec::PQ_None &&
1780        ParmDecl.getIdentifier() == 0 && ParmDecl.getNumTypeObjects() == 0) {
1781      // Completely missing, emit error.
1782      Diag(DSStart, diag::err_missing_param);
1783    } else {
1784      // Otherwise, we have something.  Add it and let semantic analysis try
1785      // to grok it and add the result to the ParamInfo we are building.
1786
1787      // Inform the actions module about the parameter declarator, so it gets
1788      // added to the current scope.
1789      DeclTy *Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
1790
1791      // Parse the default argument, if any. We parse the default
1792      // arguments in all dialects; the semantic analysis in
1793      // ActOnParamDefaultArgument will reject the default argument in
1794      // C.
1795      if (Tok.is(tok::equal)) {
1796        SourceLocation EqualLoc = Tok.getLocation();
1797
1798        // Consume the '='.
1799        ConsumeToken();
1800
1801        // Parse the default argument
1802        ExprResult DefArgResult = ParseAssignmentExpression();
1803        if (DefArgResult.isInvalid) {
1804          SkipUntil(tok::comma, tok::r_paren, true, true);
1805        } else {
1806          // Inform the actions module about the default argument
1807          Actions.ActOnParamDefaultArgument(Param, EqualLoc, DefArgResult.Val);
1808        }
1809      }
1810
1811      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1812                             ParmDecl.getIdentifierLoc(), Param));
1813    }
1814
1815    // If the next token is a comma, consume it and keep reading arguments.
1816    if (Tok.isNot(tok::comma)) break;
1817
1818    // Consume the comma.
1819    ConsumeToken();
1820  }
1821
1822  // Leave prototype scope.
1823  ExitScope();
1824
1825  // If we have the closing ')', eat it.
1826  MatchRHSPunctuation(tok::r_paren, LParenLoc);
1827
1828  DeclSpec DS;
1829  if (getLang().CPlusPlus) {
1830    // Parse cv-qualifier-seq[opt].
1831    ParseTypeQualifierListOpt(DS);
1832
1833    // Parse exception-specification[opt].
1834    if (Tok.is(tok::kw_throw))
1835      ParseExceptionSpecification();
1836  }
1837
1838  // Remember that we parsed a function type, and remember the attributes.
1839  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
1840                                             &ParamInfo[0], ParamInfo.size(),
1841                                             DS.getTypeQualifiers(),
1842                                             LParenLoc));
1843}
1844
1845/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
1846/// we found a K&R-style identifier list instead of a type argument list.  The
1847/// current token is known to be the first identifier in the list.
1848///
1849///       identifier-list: [C99 6.7.5]
1850///         identifier
1851///         identifier-list ',' identifier
1852///
1853void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
1854                                                   Declarator &D) {
1855  // Build up an array of information about the parsed arguments.
1856  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1857  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
1858
1859  // If there was no identifier specified for the declarator, either we are in
1860  // an abstract-declarator, or we are in a parameter declarator which was found
1861  // to be abstract.  In abstract-declarators, identifier lists are not valid:
1862  // diagnose this.
1863  if (!D.getIdentifier())
1864    Diag(Tok, diag::ext_ident_list_in_param);
1865
1866  // Tok is known to be the first identifier in the list.  Remember this
1867  // identifier in ParamInfo.
1868  ParamsSoFar.insert(Tok.getIdentifierInfo());
1869  ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
1870                                                 Tok.getLocation(), 0));
1871
1872  ConsumeToken();  // eat the first identifier.
1873
1874  while (Tok.is(tok::comma)) {
1875    // Eat the comma.
1876    ConsumeToken();
1877
1878    // If this isn't an identifier, report the error and skip until ')'.
1879    if (Tok.isNot(tok::identifier)) {
1880      Diag(Tok, diag::err_expected_ident);
1881      SkipUntil(tok::r_paren);
1882      return;
1883    }
1884
1885    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
1886
1887    // Reject 'typedef int y; int test(x, y)', but continue parsing.
1888    if (Actions.isTypeName(*ParmII, CurScope))
1889      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
1890
1891    // Verify that the argument identifier has not already been mentioned.
1892    if (!ParamsSoFar.insert(ParmII)) {
1893      Diag(Tok, diag::err_param_redefinition) << ParmII;
1894    } else {
1895      // Remember this identifier in ParamInfo.
1896      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1897                                                     Tok.getLocation(), 0));
1898    }
1899
1900    // Eat the identifier.
1901    ConsumeToken();
1902  }
1903
1904  // Remember that we parsed a function type, and remember the attributes.  This
1905  // function type is always a K&R style function type, which is not varargs and
1906  // has no prototype.
1907  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
1908                                             &ParamInfo[0], ParamInfo.size(),
1909                                             /*TypeQuals*/0, LParenLoc));
1910
1911  // If we have the closing ')', eat it and we're done.
1912  MatchRHSPunctuation(tok::r_paren, LParenLoc);
1913}
1914
1915/// [C90]   direct-declarator '[' constant-expression[opt] ']'
1916/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
1917/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
1918/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
1919/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
1920void Parser::ParseBracketDeclarator(Declarator &D) {
1921  SourceLocation StartLoc = ConsumeBracket();
1922
1923  // If valid, this location is the position where we read the 'static' keyword.
1924  SourceLocation StaticLoc;
1925  if (Tok.is(tok::kw_static))
1926    StaticLoc = ConsumeToken();
1927
1928  // If there is a type-qualifier-list, read it now.
1929  DeclSpec DS;
1930  ParseTypeQualifierListOpt(DS);
1931
1932  // If we haven't already read 'static', check to see if there is one after the
1933  // type-qualifier-list.
1934  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
1935    StaticLoc = ConsumeToken();
1936
1937  // Handle "direct-declarator [ type-qual-list[opt] * ]".
1938  bool isStar = false;
1939  ExprResult NumElements(false);
1940
1941  // Handle the case where we have '[*]' as the array size.  However, a leading
1942  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
1943  // the the token after the star is a ']'.  Since stars in arrays are
1944  // infrequent, use of lookahead is not costly here.
1945  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
1946    ConsumeToken();  // Eat the '*'.
1947
1948    if (StaticLoc.isValid())
1949      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
1950    StaticLoc = SourceLocation();  // Drop the static.
1951    isStar = true;
1952  } else if (Tok.isNot(tok::r_square)) {
1953    // Parse the assignment-expression now.
1954    NumElements = ParseAssignmentExpression();
1955  }
1956
1957  // If there was an error parsing the assignment-expression, recover.
1958  if (NumElements.isInvalid) {
1959    // If the expression was invalid, skip it.
1960    SkipUntil(tok::r_square);
1961    return;
1962  }
1963
1964  MatchRHSPunctuation(tok::r_square, StartLoc);
1965
1966  // If C99 isn't enabled, emit an ext-warn if the arg list wasn't empty and if
1967  // it was not a constant expression.
1968  if (!getLang().C99) {
1969    // TODO: check C90 array constant exprness.
1970    if (isStar || StaticLoc.isValid() ||
1971        0/*TODO: NumElts is not a C90 constantexpr */)
1972      Diag(StartLoc, diag::ext_c99_array_usage);
1973  }
1974
1975  // Remember that we parsed a pointer type, and remember the type-quals.
1976  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
1977                                          StaticLoc.isValid(), isStar,
1978                                          NumElements.Val, StartLoc));
1979}
1980
1981/// [GNU]   typeof-specifier:
1982///           typeof ( expressions )
1983///           typeof ( type-name )
1984/// [GNU/C++] typeof unary-expression
1985///
1986void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
1987  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
1988  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1989  SourceLocation StartLoc = ConsumeToken();
1990
1991  if (Tok.isNot(tok::l_paren)) {
1992    if (!getLang().CPlusPlus) {
1993      Diag(Tok, diag::err_expected_lparen_after_id) << BuiltinII;
1994      return;
1995    }
1996
1997    ExprResult Result = ParseCastExpression(true/*isUnaryExpression*/);
1998    if (Result.isInvalid)
1999      return;
2000
2001    const char *PrevSpec = 0;
2002    // Check for duplicate type specifiers.
2003    if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
2004                           Result.Val))
2005      Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2006
2007    // FIXME: Not accurate, the range gets one token more than it should.
2008    DS.SetRangeEnd(Tok.getLocation());
2009    return;
2010  }
2011
2012  SourceLocation LParenLoc = ConsumeParen(), RParenLoc;
2013
2014  if (isTypeIdInParens()) {
2015    TypeTy *Ty = ParseTypeName();
2016
2017    assert(Ty && "Parser::ParseTypeofSpecifier(): missing type");
2018
2019    if (Tok.isNot(tok::r_paren)) {
2020      MatchRHSPunctuation(tok::r_paren, LParenLoc);
2021      return;
2022    }
2023    RParenLoc = ConsumeParen();
2024    const char *PrevSpec = 0;
2025    // Check for duplicate type specifiers (e.g. "int typeof(int)").
2026    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, Ty))
2027      Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2028  } else { // we have an expression.
2029    ExprResult Result = ParseExpression();
2030    ExprGuard ResultGuard(Actions, Result);
2031
2032    if (Result.isInvalid || Tok.isNot(tok::r_paren)) {
2033      MatchRHSPunctuation(tok::r_paren, LParenLoc);
2034      return;
2035    }
2036    RParenLoc = ConsumeParen();
2037    const char *PrevSpec = 0;
2038    // Check for duplicate type specifiers (e.g. "int typeof(int)").
2039    if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
2040                           ResultGuard.take()))
2041      Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
2042  }
2043  DS.SetRangeEnd(RParenLoc);
2044}
2045
2046
2047