ParseDecl.cpp revision 198092
1193326Sed//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements the Declaration portions of the Parser interfaces.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "clang/Parse/Parser.h"
15193326Sed#include "clang/Parse/ParseDiagnostic.h"
16193326Sed#include "clang/Parse/Scope.h"
17193326Sed#include "ExtensionRAIIObject.h"
18193326Sed#include "llvm/ADT/SmallSet.h"
19193326Sedusing namespace clang;
20193326Sed
21193326Sed//===----------------------------------------------------------------------===//
22193326Sed// C99 6.7: Declarations.
23193326Sed//===----------------------------------------------------------------------===//
24193326Sed
25193326Sed/// ParseTypeName
26193326Sed///       type-name: [C99 6.7.6]
27193326Sed///         specifier-qualifier-list abstract-declarator[opt]
28193326Sed///
29193326Sed/// Called type-id in C++.
30193326SedAction::TypeResult Parser::ParseTypeName(SourceRange *Range) {
31193326Sed  // Parse the common declaration-specifiers piece.
32193326Sed  DeclSpec DS;
33193326Sed  ParseSpecifierQualifierList(DS);
34193326Sed
35193326Sed  // Parse the abstract-declarator, if present.
36193326Sed  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
37193326Sed  ParseDeclarator(DeclaratorInfo);
38193326Sed  if (Range)
39193326Sed    *Range = DeclaratorInfo.getSourceRange();
40193326Sed
41193326Sed  if (DeclaratorInfo.isInvalidType())
42193326Sed    return true;
43193326Sed
44193326Sed  return Actions.ActOnTypeName(CurScope, DeclaratorInfo);
45193326Sed}
46193326Sed
47193326Sed/// ParseAttributes - Parse a non-empty attributes list.
48193326Sed///
49193326Sed/// [GNU] attributes:
50193326Sed///         attribute
51193326Sed///         attributes attribute
52193326Sed///
53193326Sed/// [GNU]  attribute:
54193326Sed///          '__attribute__' '(' '(' attribute-list ')' ')'
55193326Sed///
56193326Sed/// [GNU]  attribute-list:
57193326Sed///          attrib
58193326Sed///          attribute_list ',' attrib
59193326Sed///
60193326Sed/// [GNU]  attrib:
61193326Sed///          empty
62193326Sed///          attrib-name
63193326Sed///          attrib-name '(' identifier ')'
64193326Sed///          attrib-name '(' identifier ',' nonempty-expr-list ')'
65193326Sed///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
66193326Sed///
67193326Sed/// [GNU]  attrib-name:
68193326Sed///          identifier
69193326Sed///          typespec
70193326Sed///          typequal
71193326Sed///          storageclass
72198092Srdivacky///
73193326Sed/// FIXME: The GCC grammar/code for this construct implies we need two
74198092Srdivacky/// token lookahead. Comment from gcc: "If they start with an identifier
75198092Srdivacky/// which is followed by a comma or close parenthesis, then the arguments
76193326Sed/// start with that identifier; otherwise they are an expression list."
77193326Sed///
78193326Sed/// At the moment, I am not doing 2 token lookahead. I am also unaware of
79193326Sed/// any attributes that don't work (based on my limited testing). Most
80193326Sed/// attributes are very simple in practice. Until we find a bug, I don't see
81193326Sed/// a pressing need to implement the 2 token lookahead.
82193326Sed
83193326SedAttributeList *Parser::ParseAttributes(SourceLocation *EndLoc) {
84193326Sed  assert(Tok.is(tok::kw___attribute) && "Not an attribute list!");
85198092Srdivacky
86193326Sed  AttributeList *CurrAttr = 0;
87198092Srdivacky
88193326Sed  while (Tok.is(tok::kw___attribute)) {
89193326Sed    ConsumeToken();
90193326Sed    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
91193326Sed                         "attribute")) {
92193326Sed      SkipUntil(tok::r_paren, true); // skip until ) or ;
93193326Sed      return CurrAttr;
94193326Sed    }
95193326Sed    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
96193326Sed      SkipUntil(tok::r_paren, true); // skip until ) or ;
97193326Sed      return CurrAttr;
98193326Sed    }
99193326Sed    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
100193326Sed    while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
101193326Sed           Tok.is(tok::comma)) {
102198092Srdivacky
103198092Srdivacky      if (Tok.is(tok::comma)) {
104193326Sed        // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
105193326Sed        ConsumeToken();
106193326Sed        continue;
107193326Sed      }
108193326Sed      // we have an identifier or declaration specifier (const, int, etc.)
109193326Sed      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
110193326Sed      SourceLocation AttrNameLoc = ConsumeToken();
111198092Srdivacky
112193326Sed      // check if we have a "paramterized" attribute
113193326Sed      if (Tok.is(tok::l_paren)) {
114193326Sed        ConsumeParen(); // ignore the left paren loc for now
115198092Srdivacky
116193326Sed        if (Tok.is(tok::identifier)) {
117193326Sed          IdentifierInfo *ParmName = Tok.getIdentifierInfo();
118193326Sed          SourceLocation ParmLoc = ConsumeToken();
119198092Srdivacky
120198092Srdivacky          if (Tok.is(tok::r_paren)) {
121193326Sed            // __attribute__(( mode(byte) ))
122193326Sed            ConsumeParen(); // ignore the right paren loc for now
123198092Srdivacky            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
124193326Sed                                         ParmName, ParmLoc, 0, 0, CurrAttr);
125193326Sed          } else if (Tok.is(tok::comma)) {
126193326Sed            ConsumeToken();
127193326Sed            // __attribute__(( format(printf, 1, 2) ))
128193326Sed            ExprVector ArgExprs(Actions);
129193326Sed            bool ArgExprsOk = true;
130198092Srdivacky
131193326Sed            // now parse the non-empty comma separated list of expressions
132193326Sed            while (1) {
133193326Sed              OwningExprResult ArgExpr(ParseAssignmentExpression());
134193326Sed              if (ArgExpr.isInvalid()) {
135193326Sed                ArgExprsOk = false;
136193326Sed                SkipUntil(tok::r_paren);
137193326Sed                break;
138193326Sed              } else {
139193326Sed                ArgExprs.push_back(ArgExpr.release());
140193326Sed              }
141193326Sed              if (Tok.isNot(tok::comma))
142193326Sed                break;
143193326Sed              ConsumeToken(); // Eat the comma, move to the next argument
144193326Sed            }
145193326Sed            if (ArgExprsOk && Tok.is(tok::r_paren)) {
146193326Sed              ConsumeParen(); // ignore the right paren loc for now
147198092Srdivacky              CurrAttr = new AttributeList(AttrName, AttrNameLoc, ParmName,
148193326Sed                           ParmLoc, ArgExprs.take(), ArgExprs.size(), CurrAttr);
149193326Sed            }
150193326Sed          }
151193326Sed        } else { // not an identifier
152195099Sed          switch (Tok.getKind()) {
153195099Sed          case tok::r_paren:
154193326Sed          // parse a possibly empty comma separated list of expressions
155193326Sed            // __attribute__(( nonnull() ))
156193326Sed            ConsumeParen(); // ignore the right paren loc for now
157198092Srdivacky            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
158193326Sed                                         0, SourceLocation(), 0, 0, CurrAttr);
159195099Sed            break;
160195099Sed          case tok::kw_char:
161195099Sed          case tok::kw_wchar_t:
162198092Srdivacky          case tok::kw_char16_t:
163198092Srdivacky          case tok::kw_char32_t:
164195099Sed          case tok::kw_bool:
165195099Sed          case tok::kw_short:
166195099Sed          case tok::kw_int:
167195099Sed          case tok::kw_long:
168195099Sed          case tok::kw_signed:
169195099Sed          case tok::kw_unsigned:
170195099Sed          case tok::kw_float:
171195099Sed          case tok::kw_double:
172195099Sed          case tok::kw_void:
173195099Sed          case tok::kw_typeof:
174195099Sed            // If it's a builtin type name, eat it and expect a rparen
175195099Sed            // __attribute__(( vec_type_hint(char) ))
176195099Sed            ConsumeToken();
177198092Srdivacky            CurrAttr = new AttributeList(AttrName, AttrNameLoc,
178195099Sed                                         0, SourceLocation(), 0, 0, CurrAttr);
179195099Sed            if (Tok.is(tok::r_paren))
180195099Sed              ConsumeParen();
181195099Sed            break;
182195099Sed          default:
183193326Sed            // __attribute__(( aligned(16) ))
184193326Sed            ExprVector ArgExprs(Actions);
185193326Sed            bool ArgExprsOk = true;
186198092Srdivacky
187193326Sed            // now parse the list of expressions
188193326Sed            while (1) {
189193326Sed              OwningExprResult ArgExpr(ParseAssignmentExpression());
190193326Sed              if (ArgExpr.isInvalid()) {
191193326Sed                ArgExprsOk = false;
192193326Sed                SkipUntil(tok::r_paren);
193193326Sed                break;
194193326Sed              } else {
195193326Sed                ArgExprs.push_back(ArgExpr.release());
196193326Sed              }
197193326Sed              if (Tok.isNot(tok::comma))
198193326Sed                break;
199193326Sed              ConsumeToken(); // Eat the comma, move to the next argument
200193326Sed            }
201193326Sed            // Match the ')'.
202193326Sed            if (ArgExprsOk && Tok.is(tok::r_paren)) {
203193326Sed              ConsumeParen(); // ignore the right paren loc for now
204193326Sed              CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
205193326Sed                           SourceLocation(), ArgExprs.take(), ArgExprs.size(),
206193326Sed                           CurrAttr);
207193326Sed            }
208195099Sed            break;
209193326Sed          }
210193326Sed        }
211193326Sed      } else {
212198092Srdivacky        CurrAttr = new AttributeList(AttrName, AttrNameLoc,
213193326Sed                                     0, SourceLocation(), 0, 0, CurrAttr);
214193326Sed      }
215193326Sed    }
216193326Sed    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
217193326Sed      SkipUntil(tok::r_paren, false);
218193326Sed    SourceLocation Loc = Tok.getLocation();;
219193326Sed    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
220193326Sed      SkipUntil(tok::r_paren, false);
221193326Sed    }
222193326Sed    if (EndLoc)
223193326Sed      *EndLoc = Loc;
224193326Sed  }
225193326Sed  return CurrAttr;
226193326Sed}
227193326Sed
228193725Sed/// ParseMicrosoftDeclSpec - Parse an __declspec construct
229193725Sed///
230193725Sed/// [MS] decl-specifier:
231193725Sed///             __declspec ( extended-decl-modifier-seq )
232193725Sed///
233193725Sed/// [MS] extended-decl-modifier-seq:
234193725Sed///             extended-decl-modifier[opt]
235193725Sed///             extended-decl-modifier extended-decl-modifier-seq
236193725Sed
237194179SedAttributeList* Parser::ParseMicrosoftDeclSpec(AttributeList *CurrAttr) {
238193326Sed  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
239193725Sed
240193326Sed  ConsumeToken();
241193725Sed  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
242193725Sed                       "declspec")) {
243193725Sed    SkipUntil(tok::r_paren, true); // skip until ) or ;
244193725Sed    return CurrAttr;
245193725Sed  }
246194179Sed  while (Tok.getIdentifierInfo()) {
247193725Sed    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
248193725Sed    SourceLocation AttrNameLoc = ConsumeToken();
249193725Sed    if (Tok.is(tok::l_paren)) {
250193725Sed      ConsumeParen();
251193725Sed      // FIXME: This doesn't parse __declspec(property(get=get_func_name))
252193725Sed      // correctly.
253193725Sed      OwningExprResult ArgExpr(ParseAssignmentExpression());
254193725Sed      if (!ArgExpr.isInvalid()) {
255193725Sed        ExprTy* ExprList = ArgExpr.take();
256193725Sed        CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
257193725Sed                                     SourceLocation(), &ExprList, 1,
258193725Sed                                     CurrAttr, true);
259193725Sed      }
260193725Sed      if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
261193725Sed        SkipUntil(tok::r_paren, false);
262193725Sed    } else {
263193725Sed      CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0, SourceLocation(),
264193725Sed                                   0, 0, CurrAttr, true);
265193725Sed    }
266193725Sed  }
267193725Sed  if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
268193725Sed    SkipUntil(tok::r_paren, false);
269194179Sed  return CurrAttr;
270193326Sed}
271193326Sed
272194179SedAttributeList* Parser::ParseMicrosoftTypeAttributes(AttributeList *CurrAttr) {
273194179Sed  // Treat these like attributes
274194179Sed  // FIXME: Allow Sema to distinguish between these and real attributes!
275194179Sed  while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
276194179Sed         Tok.is(tok::kw___cdecl)    || Tok.is(tok::kw___ptr64) ||
277194179Sed         Tok.is(tok::kw___w64)) {
278194179Sed    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
279194179Sed    SourceLocation AttrNameLoc = ConsumeToken();
280194179Sed    if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64))
281194179Sed      // FIXME: Support these properly!
282194179Sed      continue;
283194179Sed    CurrAttr = new AttributeList(AttrName, AttrNameLoc, 0,
284194179Sed                                 SourceLocation(), 0, 0, CurrAttr, true);
285194179Sed  }
286194179Sed  return CurrAttr;
287194179Sed}
288194179Sed
289193326Sed/// ParseDeclaration - Parse a full 'declaration', which consists of
290193326Sed/// declaration-specifiers, some number of declarators, and a semicolon.
291193326Sed/// 'Context' should be a Declarator::TheContext value.  This returns the
292193326Sed/// location of the semicolon in DeclEnd.
293193326Sed///
294193326Sed///       declaration: [C99 6.7]
295193326Sed///         block-declaration ->
296193326Sed///           simple-declaration
297193326Sed///           others                   [FIXME]
298193326Sed/// [C++]   template-declaration
299193326Sed/// [C++]   namespace-definition
300193326Sed/// [C++]   using-directive
301194711Sed/// [C++]   using-declaration
302193326Sed/// [C++0x] static_assert-declaration
303193326Sed///         others... [FIXME]
304193326Sed///
305193326SedParser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
306193326Sed                                                SourceLocation &DeclEnd) {
307193326Sed  DeclPtrTy SingleDecl;
308193326Sed  switch (Tok.getKind()) {
309193326Sed  case tok::kw_template:
310193326Sed  case tok::kw_export:
311193326Sed    SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
312193326Sed    break;
313193326Sed  case tok::kw_namespace:
314193326Sed    SingleDecl = ParseNamespace(Context, DeclEnd);
315193326Sed    break;
316193326Sed  case tok::kw_using:
317193326Sed    SingleDecl = ParseUsingDirectiveOrDeclaration(Context, DeclEnd);
318193326Sed    break;
319193326Sed  case tok::kw_static_assert:
320193326Sed    SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
321193326Sed    break;
322193326Sed  default:
323193326Sed    return ParseSimpleDeclaration(Context, DeclEnd);
324193326Sed  }
325198092Srdivacky
326193326Sed  // This routine returns a DeclGroup, if the thing we parsed only contains a
327193326Sed  // single decl, convert it now.
328193326Sed  return Actions.ConvertDeclToDeclGroup(SingleDecl);
329193326Sed}
330193326Sed
331193326Sed///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
332193326Sed///         declaration-specifiers init-declarator-list[opt] ';'
333193326Sed///[C90/C++]init-declarator-list ';'                             [TODO]
334193326Sed/// [OMP]   threadprivate-directive                              [TODO]
335193326Sed///
336193326Sed/// If RequireSemi is false, this does not check for a ';' at the end of the
337193326Sed/// declaration.
338193326SedParser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(unsigned Context,
339193326Sed                                                      SourceLocation &DeclEnd,
340193326Sed                                                      bool RequireSemi) {
341193326Sed  // Parse the common declaration-specifiers piece.
342193326Sed  DeclSpec DS;
343193326Sed  ParseDeclarationSpecifiers(DS);
344198092Srdivacky
345193326Sed  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
346193326Sed  // declaration-specifiers init-declarator-list[opt] ';'
347193326Sed  if (Tok.is(tok::semi)) {
348193326Sed    ConsumeToken();
349193326Sed    DeclPtrTy TheDecl = Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
350193326Sed    return Actions.ConvertDeclToDeclGroup(TheDecl);
351193326Sed  }
352198092Srdivacky
353193326Sed  Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
354193326Sed  ParseDeclarator(DeclaratorInfo);
355198092Srdivacky
356193326Sed  DeclGroupPtrTy DG =
357193326Sed    ParseInitDeclaratorListAfterFirstDeclarator(DeclaratorInfo);
358193326Sed
359193326Sed  DeclEnd = Tok.getLocation();
360198092Srdivacky
361193326Sed  // If the client wants to check what comes after the declaration, just return
362193326Sed  // immediately without checking anything!
363193326Sed  if (!RequireSemi) return DG;
364198092Srdivacky
365193326Sed  if (Tok.is(tok::semi)) {
366193326Sed    ConsumeToken();
367193326Sed    return DG;
368193326Sed  }
369198092Srdivacky
370198092Srdivacky  Diag(Tok, diag::err_expected_semi_declaration);
371193326Sed  // Skip to end of block or statement
372193326Sed  SkipUntil(tok::r_brace, true, true);
373193326Sed  if (Tok.is(tok::semi))
374193326Sed    ConsumeToken();
375193326Sed  return DG;
376193326Sed}
377193326Sed
378193326Sed/// \brief Parse 'declaration' after parsing 'declaration-specifiers
379193326Sed/// declarator'. This method parses the remainder of the declaration
380193326Sed/// (including any attributes or initializer, among other things) and
381193326Sed/// finalizes the declaration.
382193326Sed///
383193326Sed///       init-declarator: [C99 6.7]
384193326Sed///         declarator
385193326Sed///         declarator '=' initializer
386193326Sed/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
387193326Sed/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
388193326Sed/// [C++]   declarator initializer[opt]
389193326Sed///
390193326Sed/// [C++] initializer:
391193326Sed/// [C++]   '=' initializer-clause
392193326Sed/// [C++]   '(' expression-list ')'
393193326Sed/// [C++0x] '=' 'default'                                                [TODO]
394193326Sed/// [C++0x] '=' 'delete'
395193326Sed///
396193326Sed/// According to the standard grammar, =default and =delete are function
397193326Sed/// definitions, but that definitely doesn't fit with the parser here.
398193326Sed///
399195099SedParser::DeclPtrTy Parser::ParseDeclarationAfterDeclarator(Declarator &D,
400195099Sed                                     const ParsedTemplateInfo &TemplateInfo) {
401193326Sed  // If a simple-asm-expr is present, parse it.
402193326Sed  if (Tok.is(tok::kw_asm)) {
403193326Sed    SourceLocation Loc;
404193326Sed    OwningExprResult AsmLabel(ParseSimpleAsm(&Loc));
405193326Sed    if (AsmLabel.isInvalid()) {
406193326Sed      SkipUntil(tok::semi, true, true);
407193326Sed      return DeclPtrTy();
408193326Sed    }
409198092Srdivacky
410193326Sed    D.setAsmLabel(AsmLabel.release());
411193326Sed    D.SetRangeEnd(Loc);
412193326Sed  }
413198092Srdivacky
414193326Sed  // If attributes are present, parse them.
415193326Sed  if (Tok.is(tok::kw___attribute)) {
416193326Sed    SourceLocation Loc;
417193326Sed    AttributeList *AttrList = ParseAttributes(&Loc);
418193326Sed    D.AddAttributes(AttrList, Loc);
419193326Sed  }
420198092Srdivacky
421193326Sed  // Inform the current actions module that we just parsed this declarator.
422198092Srdivacky  DeclPtrTy ThisDecl;
423198092Srdivacky  switch (TemplateInfo.Kind) {
424198092Srdivacky  case ParsedTemplateInfo::NonTemplate:
425198092Srdivacky    ThisDecl = Actions.ActOnDeclarator(CurScope, D);
426198092Srdivacky    break;
427198092Srdivacky
428198092Srdivacky  case ParsedTemplateInfo::Template:
429198092Srdivacky  case ParsedTemplateInfo::ExplicitSpecialization:
430198092Srdivacky    ThisDecl = Actions.ActOnTemplateDeclarator(CurScope,
431195099Sed                             Action::MultiTemplateParamsArg(Actions,
432195099Sed                                          TemplateInfo.TemplateParams->data(),
433195099Sed                                          TemplateInfo.TemplateParams->size()),
434198092Srdivacky                                               D);
435198092Srdivacky    break;
436198092Srdivacky
437198092Srdivacky  case ParsedTemplateInfo::ExplicitInstantiation: {
438198092Srdivacky    Action::DeclResult ThisRes
439198092Srdivacky      = Actions.ActOnExplicitInstantiation(CurScope,
440198092Srdivacky                                           TemplateInfo.ExternLoc,
441198092Srdivacky                                           TemplateInfo.TemplateLoc,
442198092Srdivacky                                           D);
443198092Srdivacky    if (ThisRes.isInvalid()) {
444198092Srdivacky      SkipUntil(tok::semi, true, true);
445198092Srdivacky      return DeclPtrTy();
446198092Srdivacky    }
447198092Srdivacky
448198092Srdivacky    ThisDecl = ThisRes.get();
449198092Srdivacky    break;
450198092Srdivacky    }
451198092Srdivacky  }
452198092Srdivacky
453193326Sed  // Parse declarator '=' initializer.
454193326Sed  if (Tok.is(tok::equal)) {
455193326Sed    ConsumeToken();
456193326Sed    if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
457193326Sed      SourceLocation DelLoc = ConsumeToken();
458193326Sed      Actions.SetDeclDeleted(ThisDecl, DelLoc);
459193326Sed    } else {
460194613Sed      if (getLang().CPlusPlus)
461194613Sed        Actions.ActOnCXXEnterDeclInitializer(CurScope, ThisDecl);
462194613Sed
463193326Sed      OwningExprResult Init(ParseInitializer());
464194613Sed
465194613Sed      if (getLang().CPlusPlus)
466194613Sed        Actions.ActOnCXXExitDeclInitializer(CurScope, ThisDecl);
467194613Sed
468193326Sed      if (Init.isInvalid()) {
469193326Sed        SkipUntil(tok::semi, true, true);
470193326Sed        return DeclPtrTy();
471193326Sed      }
472198092Srdivacky      Actions.AddInitializerToDecl(ThisDecl, move(Init));
473193326Sed    }
474193326Sed  } else if (Tok.is(tok::l_paren)) {
475193326Sed    // Parse C++ direct initializer: '(' expression-list ')'
476193326Sed    SourceLocation LParenLoc = ConsumeParen();
477193326Sed    ExprVector Exprs(Actions);
478193326Sed    CommaLocsTy CommaLocs;
479193326Sed
480193326Sed    if (ParseExpressionList(Exprs, CommaLocs)) {
481193326Sed      SkipUntil(tok::r_paren);
482193326Sed    } else {
483193326Sed      // Match the ')'.
484193326Sed      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
485193326Sed
486193326Sed      assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
487193326Sed             "Unexpected number of commas!");
488193326Sed      Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc,
489193326Sed                                            move_arg(Exprs),
490193326Sed                                            CommaLocs.data(), RParenLoc);
491193326Sed    }
492193326Sed  } else {
493198092Srdivacky    bool TypeContainsUndeducedAuto =
494198092Srdivacky      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
495198092Srdivacky    Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsUndeducedAuto);
496193326Sed  }
497193326Sed
498193326Sed  return ThisDecl;
499193326Sed}
500193326Sed
501193326Sed/// ParseInitDeclaratorListAfterFirstDeclarator - Parse 'declaration' after
502193326Sed/// parsing 'declaration-specifiers declarator'.  This method is split out this
503193326Sed/// way to handle the ambiguity between top-level function-definitions and
504193326Sed/// declarations.
505193326Sed///
506193326Sed///       init-declarator-list: [C99 6.7]
507193326Sed///         init-declarator
508193326Sed///         init-declarator-list ',' init-declarator
509193326Sed///
510193326Sed/// According to the standard grammar, =default and =delete are function
511193326Sed/// definitions, but that definitely doesn't fit with the parser here.
512193326Sed///
513193326SedParser::DeclGroupPtrTy Parser::
514193326SedParseInitDeclaratorListAfterFirstDeclarator(Declarator &D) {
515193326Sed  // Declarators may be grouped together ("int X, *Y, Z();"). Remember the decls
516193326Sed  // that we parse together here.
517193326Sed  llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
518198092Srdivacky
519193326Sed  // At this point, we know that it is not a function definition.  Parse the
520193326Sed  // rest of the init-declarator-list.
521193326Sed  while (1) {
522193326Sed    DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(D);
523193326Sed    if (ThisDecl.get())
524193326Sed      DeclsInGroup.push_back(ThisDecl);
525198092Srdivacky
526193326Sed    // If we don't have a comma, it is either the end of the list (a ';') or an
527193326Sed    // error, bail out.
528193326Sed    if (Tok.isNot(tok::comma))
529193326Sed      break;
530198092Srdivacky
531193326Sed    // Consume the comma.
532193326Sed    ConsumeToken();
533198092Srdivacky
534193326Sed    // Parse the next declarator.
535193326Sed    D.clear();
536198092Srdivacky
537193326Sed    // Accept attributes in an init-declarator.  In the first declarator in a
538193326Sed    // declaration, these would be part of the declspec.  In subsequent
539193326Sed    // declarators, they become part of the declarator itself, so that they
540193326Sed    // don't apply to declarators after *this* one.  Examples:
541193326Sed    //    short __attribute__((common)) var;    -> declspec
542193326Sed    //    short var __attribute__((common));    -> declarator
543193326Sed    //    short x, __attribute__((common)) var;    -> declarator
544193326Sed    if (Tok.is(tok::kw___attribute)) {
545193326Sed      SourceLocation Loc;
546193326Sed      AttributeList *AttrList = ParseAttributes(&Loc);
547193326Sed      D.AddAttributes(AttrList, Loc);
548193326Sed    }
549198092Srdivacky
550193326Sed    ParseDeclarator(D);
551193326Sed  }
552198092Srdivacky
553193326Sed  return Actions.FinalizeDeclaratorGroup(CurScope, D.getDeclSpec(),
554193326Sed                                         DeclsInGroup.data(),
555193326Sed                                         DeclsInGroup.size());
556193326Sed}
557193326Sed
558193326Sed/// ParseSpecifierQualifierList
559193326Sed///        specifier-qualifier-list:
560193326Sed///          type-specifier specifier-qualifier-list[opt]
561193326Sed///          type-qualifier specifier-qualifier-list[opt]
562193326Sed/// [GNU]    attributes     specifier-qualifier-list[opt]
563193326Sed///
564193326Sedvoid Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
565193326Sed  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
566193326Sed  /// parse declaration-specifiers and complain about extra stuff.
567193326Sed  ParseDeclarationSpecifiers(DS);
568198092Srdivacky
569193326Sed  // Validate declspec for type-name.
570193326Sed  unsigned Specs = DS.getParsedSpecifiers();
571193326Sed  if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
572193326Sed      !DS.getAttributes())
573193326Sed    Diag(Tok, diag::err_typename_requires_specqual);
574198092Srdivacky
575193326Sed  // Issue diagnostic and remove storage class if present.
576193326Sed  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
577193326Sed    if (DS.getStorageClassSpecLoc().isValid())
578193326Sed      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
579193326Sed    else
580193326Sed      Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
581193326Sed    DS.ClearStorageClassSpecs();
582193326Sed  }
583198092Srdivacky
584193326Sed  // Issue diagnostic and remove function specfier if present.
585193326Sed  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
586193326Sed    if (DS.isInlineSpecified())
587193326Sed      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
588193326Sed    if (DS.isVirtualSpecified())
589193326Sed      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
590193326Sed    if (DS.isExplicitSpecified())
591193326Sed      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
592193326Sed    DS.ClearFunctionSpecs();
593193326Sed  }
594193326Sed}
595193326Sed
596193326Sed/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
597193326Sed/// specified token is valid after the identifier in a declarator which
598193326Sed/// immediately follows the declspec.  For example, these things are valid:
599193326Sed///
600193326Sed///      int x   [             4];         // direct-declarator
601193326Sed///      int x   (             int y);     // direct-declarator
602193326Sed///  int(int x   )                         // direct-declarator
603193326Sed///      int x   ;                         // simple-declaration
604193326Sed///      int x   =             17;         // init-declarator-list
605193326Sed///      int x   ,             y;          // init-declarator-list
606193326Sed///      int x   __asm__       ("foo");    // init-declarator-list
607193326Sed///      int x   :             4;          // struct-declarator
608193326Sed///      int x   {             5};         // C++'0x unified initializers
609193326Sed///
610193326Sed/// This is not, because 'x' does not immediately follow the declspec (though
611193326Sed/// ')' happens to be valid anyway).
612193326Sed///    int (x)
613193326Sed///
614193326Sedstatic bool isValidAfterIdentifierInDeclarator(const Token &T) {
615193326Sed  return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
616193326Sed         T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
617193326Sed         T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
618193326Sed}
619193326Sed
620193326Sed
621193326Sed/// ParseImplicitInt - This method is called when we have an non-typename
622193326Sed/// identifier in a declspec (which normally terminates the decl spec) when
623193326Sed/// the declspec has no type specifier.  In this case, the declspec is either
624193326Sed/// malformed or is "implicit int" (in K&R and C89).
625193326Sed///
626193326Sed/// This method handles diagnosing this prettily and returns false if the
627193326Sed/// declspec is done being processed.  If it recovers and thinks there may be
628193326Sed/// other pieces of declspec after it, it returns true.
629193326Sed///
630193326Sedbool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
631193326Sed                              const ParsedTemplateInfo &TemplateInfo,
632193326Sed                              AccessSpecifier AS) {
633193326Sed  assert(Tok.is(tok::identifier) && "should have identifier");
634198092Srdivacky
635193326Sed  SourceLocation Loc = Tok.getLocation();
636193326Sed  // If we see an identifier that is not a type name, we normally would
637193326Sed  // parse it as the identifer being declared.  However, when a typename
638193326Sed  // is typo'd or the definition is not included, this will incorrectly
639193326Sed  // parse the typename as the identifier name and fall over misparsing
640193326Sed  // later parts of the diagnostic.
641193326Sed  //
642193326Sed  // As such, we try to do some look-ahead in cases where this would
643193326Sed  // otherwise be an "implicit-int" case to see if this is invalid.  For
644193326Sed  // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
645193326Sed  // an identifier with implicit int, we'd get a parse error because the
646193326Sed  // next token is obviously invalid for a type.  Parse these as a case
647193326Sed  // with an invalid type specifier.
648193326Sed  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
649198092Srdivacky
650193326Sed  // Since we know that this either implicit int (which is rare) or an
651193326Sed  // error, we'd do lookahead to try to do better recovery.
652193326Sed  if (isValidAfterIdentifierInDeclarator(NextToken())) {
653193326Sed    // If this token is valid for implicit int, e.g. "static x = 4", then
654193326Sed    // we just avoid eating the identifier, so it will be parsed as the
655193326Sed    // identifier in the declarator.
656193326Sed    return false;
657193326Sed  }
658198092Srdivacky
659193326Sed  // Otherwise, if we don't consume this token, we are going to emit an
660193326Sed  // error anyway.  Try to recover from various common problems.  Check
661193326Sed  // to see if this was a reference to a tag name without a tag specified.
662193326Sed  // This is a common problem in C (saying 'foo' instead of 'struct foo').
663193326Sed  //
664193326Sed  // C++ doesn't need this, and isTagName doesn't take SS.
665193326Sed  if (SS == 0) {
666193326Sed    const char *TagName = 0;
667193326Sed    tok::TokenKind TagKind = tok::unknown;
668198092Srdivacky
669193326Sed    switch (Actions.isTagName(*Tok.getIdentifierInfo(), CurScope)) {
670193326Sed      default: break;
671193326Sed      case DeclSpec::TST_enum:  TagName="enum"  ;TagKind=tok::kw_enum  ;break;
672193326Sed      case DeclSpec::TST_union: TagName="union" ;TagKind=tok::kw_union ;break;
673193326Sed      case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break;
674193326Sed      case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break;
675193326Sed    }
676198092Srdivacky
677193326Sed    if (TagName) {
678193326Sed      Diag(Loc, diag::err_use_of_tag_name_without_tag)
679193326Sed        << Tok.getIdentifierInfo() << TagName
680193326Sed        << CodeModificationHint::CreateInsertion(Tok.getLocation(),TagName);
681198092Srdivacky
682193326Sed      // Parse this as a tag as if the missing tag were present.
683193326Sed      if (TagKind == tok::kw_enum)
684193326Sed        ParseEnumSpecifier(Loc, DS, AS);
685193326Sed      else
686193326Sed        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
687193326Sed      return true;
688193326Sed    }
689193326Sed  }
690198092Srdivacky
691198092Srdivacky  // This is almost certainly an invalid type name. Let the action emit a
692198092Srdivacky  // diagnostic and attempt to recover.
693198092Srdivacky  Action::TypeTy *T = 0;
694198092Srdivacky  if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
695198092Srdivacky                                      CurScope, SS, T)) {
696198092Srdivacky    // The action emitted a diagnostic, so we don't have to.
697198092Srdivacky    if (T) {
698198092Srdivacky      // The action has suggested that the type T could be used. Set that as
699198092Srdivacky      // the type in the declaration specifiers, consume the would-be type
700198092Srdivacky      // name token, and we're done.
701198092Srdivacky      const char *PrevSpec;
702198092Srdivacky      unsigned DiagID;
703198092Srdivacky      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
704198092Srdivacky                         false);
705198092Srdivacky      DS.SetRangeEnd(Tok.getLocation());
706198092Srdivacky      ConsumeToken();
707198092Srdivacky
708198092Srdivacky      // There may be other declaration specifiers after this.
709198092Srdivacky      return true;
710198092Srdivacky    }
711198092Srdivacky
712198092Srdivacky    // Fall through; the action had no suggestion for us.
713198092Srdivacky  } else {
714198092Srdivacky    // The action did not emit a diagnostic, so emit one now.
715198092Srdivacky    SourceRange R;
716198092Srdivacky    if (SS) R = SS->getRange();
717198092Srdivacky    Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
718198092Srdivacky  }
719198092Srdivacky
720198092Srdivacky  // Mark this as an error.
721193326Sed  const char *PrevSpec;
722198092Srdivacky  unsigned DiagID;
723198092Srdivacky  DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
724193326Sed  DS.SetRangeEnd(Tok.getLocation());
725193326Sed  ConsumeToken();
726198092Srdivacky
727193326Sed  // TODO: Could inject an invalid typedef decl in an enclosing scope to
728193326Sed  // avoid rippling error messages on subsequent uses of the same type,
729193326Sed  // could be useful if #include was forgotten.
730193326Sed  return false;
731193326Sed}
732193326Sed
733193326Sed/// ParseDeclarationSpecifiers
734193326Sed///       declaration-specifiers: [C99 6.7]
735193326Sed///         storage-class-specifier declaration-specifiers[opt]
736193326Sed///         type-specifier declaration-specifiers[opt]
737193326Sed/// [C99]   function-specifier declaration-specifiers[opt]
738193326Sed/// [GNU]   attributes declaration-specifiers[opt]
739193326Sed///
740193326Sed///       storage-class-specifier: [C99 6.7.1]
741193326Sed///         'typedef'
742193326Sed///         'extern'
743193326Sed///         'static'
744193326Sed///         'auto'
745193326Sed///         'register'
746193326Sed/// [C++]   'mutable'
747193326Sed/// [GNU]   '__thread'
748193326Sed///       function-specifier: [C99 6.7.4]
749193326Sed/// [C99]   'inline'
750193326Sed/// [C++]   'virtual'
751193326Sed/// [C++]   'explicit'
752193326Sed///       'friend': [C++ dcl.friend]
753193326Sed
754193326Sed///
755193326Sedvoid Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
756193326Sed                                        const ParsedTemplateInfo &TemplateInfo,
757198092Srdivacky                                        AccessSpecifier AS,
758198092Srdivacky                                        DeclSpecContext DSContext) {
759198092Srdivacky  if (Tok.is(tok::code_completion)) {
760198092Srdivacky    Actions.CodeCompleteOrdinaryName(CurScope);
761198092Srdivacky    ConsumeToken();
762198092Srdivacky  }
763198092Srdivacky
764193326Sed  DS.SetRangeStart(Tok.getLocation());
765193326Sed  while (1) {
766198092Srdivacky    bool isInvalid = false;
767193326Sed    const char *PrevSpec = 0;
768198092Srdivacky    unsigned DiagID = 0;
769198092Srdivacky
770193326Sed    SourceLocation Loc = Tok.getLocation();
771193326Sed
772193326Sed    switch (Tok.getKind()) {
773198092Srdivacky    default:
774193326Sed    DoneWithDeclSpec:
775193326Sed      // If this is not a declaration specifier token, we're done reading decl
776193326Sed      // specifiers.  First verify that DeclSpec's are consistent.
777193326Sed      DS.Finish(Diags, PP);
778193326Sed      return;
779198092Srdivacky
780193326Sed    case tok::coloncolon: // ::foo::bar
781193326Sed      // Annotate C++ scope specifiers.  If we get one, loop.
782198092Srdivacky      if (TryAnnotateCXXScopeToken(true))
783193326Sed        continue;
784193326Sed      goto DoneWithDeclSpec;
785193326Sed
786193326Sed    case tok::annot_cxxscope: {
787193326Sed      if (DS.hasTypeSpecifier())
788193326Sed        goto DoneWithDeclSpec;
789193326Sed
790193326Sed      // We are looking for a qualified typename.
791193326Sed      Token Next = NextToken();
792198092Srdivacky      if (Next.is(tok::annot_template_id) &&
793193326Sed          static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
794193326Sed            ->Kind == TNK_Type_template) {
795193326Sed        // We have a qualified template-id, e.g., N::A<int>
796193326Sed        CXXScopeSpec SS;
797198092Srdivacky        ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true);
798198092Srdivacky        assert(Tok.is(tok::annot_template_id) &&
799193326Sed               "ParseOptionalCXXScopeSpecifier not working");
800193326Sed        AnnotateTemplateIdTokenAsType(&SS);
801193326Sed        continue;
802193326Sed      }
803193326Sed
804198092Srdivacky      if (Next.is(tok::annot_typename)) {
805198092Srdivacky        // FIXME: is this scope-specifier getting dropped?
806198092Srdivacky        ConsumeToken(); // the scope-specifier
807198092Srdivacky        if (Tok.getAnnotationValue())
808198092Srdivacky          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc,
809198092Srdivacky                                         PrevSpec, DiagID,
810198092Srdivacky                                         Tok.getAnnotationValue());
811198092Srdivacky        else
812198092Srdivacky          DS.SetTypeSpecError();
813198092Srdivacky        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
814198092Srdivacky        ConsumeToken(); // The typename
815198092Srdivacky      }
816198092Srdivacky
817193326Sed      if (Next.isNot(tok::identifier))
818193326Sed        goto DoneWithDeclSpec;
819193326Sed
820193326Sed      CXXScopeSpec SS;
821193326Sed      SS.setScopeRep(Tok.getAnnotationValue());
822193326Sed      SS.setRange(Tok.getAnnotationRange());
823193326Sed
824193326Sed      // If the next token is the name of the class type that the C++ scope
825193326Sed      // denotes, followed by a '(', then this is a constructor declaration.
826193326Sed      // We're done with the decl-specifiers.
827193326Sed      if (Actions.isCurrentClassName(*Next.getIdentifierInfo(),
828193326Sed                                     CurScope, &SS) &&
829193326Sed          GetLookAheadToken(2).is(tok::l_paren))
830193326Sed        goto DoneWithDeclSpec;
831193326Sed
832193326Sed      TypeTy *TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
833193326Sed                                            Next.getLocation(), CurScope, &SS);
834193326Sed
835193326Sed      // If the referenced identifier is not a type, then this declspec is
836193326Sed      // erroneous: We already checked about that it has no type specifier, and
837193326Sed      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
838198092Srdivacky      // typename.
839193326Sed      if (TypeRep == 0) {
840193326Sed        ConsumeToken();   // Eat the scope spec so the identifier is current.
841193326Sed        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
842193326Sed        goto DoneWithDeclSpec;
843193326Sed      }
844198092Srdivacky
845193326Sed      ConsumeToken(); // The C++ scope.
846193326Sed
847193326Sed      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
848198092Srdivacky                                     DiagID, TypeRep);
849193326Sed      if (isInvalid)
850193326Sed        break;
851198092Srdivacky
852193326Sed      DS.SetRangeEnd(Tok.getLocation());
853193326Sed      ConsumeToken(); // The typename.
854193326Sed
855193326Sed      continue;
856193326Sed    }
857198092Srdivacky
858193326Sed    case tok::annot_typename: {
859193326Sed      if (Tok.getAnnotationValue())
860193326Sed        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
861198092Srdivacky                                       DiagID, Tok.getAnnotationValue());
862193326Sed      else
863193326Sed        DS.SetTypeSpecError();
864193326Sed      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
865193326Sed      ConsumeToken(); // The typename
866198092Srdivacky
867193326Sed      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
868193326Sed      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
869193326Sed      // Objective-C interface.  If we don't have Objective-C or a '<', this is
870193326Sed      // just a normal reference to a typedef name.
871193326Sed      if (!Tok.is(tok::less) || !getLang().ObjC1)
872193326Sed        continue;
873198092Srdivacky
874198092Srdivacky      SourceLocation LAngleLoc, EndProtoLoc;
875193326Sed      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
876198092Srdivacky      llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
877198092Srdivacky      ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
878198092Srdivacky                                  LAngleLoc, EndProtoLoc);
879198092Srdivacky      DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
880198092Srdivacky                               ProtocolLocs.data(), LAngleLoc);
881198092Srdivacky
882193326Sed      DS.SetRangeEnd(EndProtoLoc);
883193326Sed      continue;
884193326Sed    }
885198092Srdivacky
886193326Sed      // typedef-name
887193326Sed    case tok::identifier: {
888193326Sed      // In C++, check to see if this is a scope specifier like foo::bar::, if
889193326Sed      // so handle it as such.  This is important for ctor parsing.
890198092Srdivacky      if (getLang().CPlusPlus && TryAnnotateCXXScopeToken(true))
891193326Sed        continue;
892198092Srdivacky
893193326Sed      // This identifier can only be a typedef name if we haven't already seen
894193326Sed      // a type-specifier.  Without this check we misparse:
895193326Sed      //  typedef int X; struct Y { short X; };  as 'short int'.
896193326Sed      if (DS.hasTypeSpecifier())
897193326Sed        goto DoneWithDeclSpec;
898198092Srdivacky
899193326Sed      // It has to be available as a typedef too!
900198092Srdivacky      TypeTy *TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(),
901193326Sed                                            Tok.getLocation(), CurScope);
902193326Sed
903193326Sed      // If this is not a typedef name, don't parse it as part of the declspec,
904193326Sed      // it must be an implicit int or an error.
905193326Sed      if (TypeRep == 0) {
906193326Sed        if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
907193326Sed        goto DoneWithDeclSpec;
908193326Sed      }
909193326Sed
910193326Sed      // C++: If the identifier is actually the name of the class type
911193326Sed      // being defined and the next token is a '(', then this is a
912193326Sed      // constructor declaration. We're done with the decl-specifiers
913193326Sed      // and will treat this token as an identifier.
914198092Srdivacky      if (getLang().CPlusPlus &&
915198092Srdivacky          (CurScope->isClassScope() ||
916198092Srdivacky           (CurScope->isTemplateParamScope() &&
917198092Srdivacky            CurScope->getParent()->isClassScope())) &&
918198092Srdivacky          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), CurScope) &&
919193326Sed          NextToken().getKind() == tok::l_paren)
920193326Sed        goto DoneWithDeclSpec;
921193326Sed
922193326Sed      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
923198092Srdivacky                                     DiagID, TypeRep);
924193326Sed      if (isInvalid)
925193326Sed        break;
926198092Srdivacky
927193326Sed      DS.SetRangeEnd(Tok.getLocation());
928193326Sed      ConsumeToken(); // The identifier
929193326Sed
930193326Sed      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
931193326Sed      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
932193326Sed      // Objective-C interface.  If we don't have Objective-C or a '<', this is
933193326Sed      // just a normal reference to a typedef name.
934193326Sed      if (!Tok.is(tok::less) || !getLang().ObjC1)
935193326Sed        continue;
936198092Srdivacky
937198092Srdivacky      SourceLocation LAngleLoc, EndProtoLoc;
938193326Sed      llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
939198092Srdivacky      llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
940198092Srdivacky      ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
941198092Srdivacky                                  LAngleLoc, EndProtoLoc);
942198092Srdivacky      DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
943198092Srdivacky                               ProtocolLocs.data(), LAngleLoc);
944198092Srdivacky
945193326Sed      DS.SetRangeEnd(EndProtoLoc);
946193326Sed
947193326Sed      // Need to support trailing type qualifiers (e.g. "id<p> const").
948193326Sed      // If a type specifier follows, it will be diagnosed elsewhere.
949193326Sed      continue;
950193326Sed    }
951193326Sed
952193326Sed      // type-name
953193326Sed    case tok::annot_template_id: {
954198092Srdivacky      TemplateIdAnnotation *TemplateId
955193326Sed        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
956193326Sed      if (TemplateId->Kind != TNK_Type_template) {
957193326Sed        // This template-id does not refer to a type name, so we're
958193326Sed        // done with the type-specifiers.
959193326Sed        goto DoneWithDeclSpec;
960193326Sed      }
961193326Sed
962193326Sed      // Turn the template-id annotation token into a type annotation
963193326Sed      // token, then try again to parse it as a type-specifier.
964193326Sed      AnnotateTemplateIdTokenAsType();
965193326Sed      continue;
966193326Sed    }
967193326Sed
968193326Sed    // GNU attributes support.
969193326Sed    case tok::kw___attribute:
970193326Sed      DS.AddAttributes(ParseAttributes());
971193326Sed      continue;
972193326Sed
973193326Sed    // Microsoft declspec support.
974193326Sed    case tok::kw___declspec:
975193725Sed      DS.AddAttributes(ParseMicrosoftDeclSpec());
976193326Sed      continue;
977198092Srdivacky
978193326Sed    // Microsoft single token adornments.
979193326Sed    case tok::kw___forceinline:
980194179Sed      // FIXME: Add handling here!
981194179Sed      break;
982194179Sed
983194179Sed    case tok::kw___ptr64:
984193326Sed    case tok::kw___w64:
985193326Sed    case tok::kw___cdecl:
986193326Sed    case tok::kw___stdcall:
987193326Sed    case tok::kw___fastcall:
988194179Sed      DS.AddAttributes(ParseMicrosoftTypeAttributes());
989194179Sed      continue;
990194179Sed
991193326Sed    // storage-class-specifier
992193326Sed    case tok::kw_typedef:
993198092Srdivacky      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
994198092Srdivacky                                         DiagID);
995193326Sed      break;
996193326Sed    case tok::kw_extern:
997193326Sed      if (DS.isThreadSpecified())
998193326Sed        Diag(Tok, diag::ext_thread_before) << "extern";
999198092Srdivacky      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1000198092Srdivacky                                         DiagID);
1001193326Sed      break;
1002193326Sed    case tok::kw___private_extern__:
1003193326Sed      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1004198092Srdivacky                                         PrevSpec, DiagID);
1005193326Sed      break;
1006193326Sed    case tok::kw_static:
1007193326Sed      if (DS.isThreadSpecified())
1008193326Sed        Diag(Tok, diag::ext_thread_before) << "static";
1009198092Srdivacky      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1010198092Srdivacky                                         DiagID);
1011193326Sed      break;
1012193326Sed    case tok::kw_auto:
1013195099Sed      if (getLang().CPlusPlus0x)
1014198092Srdivacky        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1015198092Srdivacky                                       DiagID);
1016195099Sed      else
1017198092Srdivacky        isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1018198092Srdivacky                                           DiagID);
1019193326Sed      break;
1020193326Sed    case tok::kw_register:
1021198092Srdivacky      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1022198092Srdivacky                                         DiagID);
1023193326Sed      break;
1024193326Sed    case tok::kw_mutable:
1025198092Srdivacky      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1026198092Srdivacky                                         DiagID);
1027193326Sed      break;
1028193326Sed    case tok::kw___thread:
1029198092Srdivacky      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1030193326Sed      break;
1031198092Srdivacky
1032193326Sed    // function-specifier
1033193326Sed    case tok::kw_inline:
1034198092Srdivacky      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1035193326Sed      break;
1036193326Sed    case tok::kw_virtual:
1037198092Srdivacky      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1038193326Sed      break;
1039193326Sed    case tok::kw_explicit:
1040198092Srdivacky      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1041193326Sed      break;
1042193326Sed
1043193326Sed    // friend
1044193326Sed    case tok::kw_friend:
1045198092Srdivacky      if (DSContext == DSC_class)
1046198092Srdivacky        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1047198092Srdivacky      else {
1048198092Srdivacky        PrevSpec = ""; // not actually used by the diagnostic
1049198092Srdivacky        DiagID = diag::err_friend_invalid_in_context;
1050198092Srdivacky        isInvalid = true;
1051198092Srdivacky      }
1052193326Sed      break;
1053198092Srdivacky
1054193326Sed    // type-specifier
1055193326Sed    case tok::kw_short:
1056198092Srdivacky      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1057198092Srdivacky                                      DiagID);
1058193326Sed      break;
1059193326Sed    case tok::kw_long:
1060193326Sed      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1061198092Srdivacky        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1062198092Srdivacky                                        DiagID);
1063193326Sed      else
1064198092Srdivacky        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1065198092Srdivacky                                        DiagID);
1066193326Sed      break;
1067193326Sed    case tok::kw_signed:
1068198092Srdivacky      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1069198092Srdivacky                                     DiagID);
1070193326Sed      break;
1071193326Sed    case tok::kw_unsigned:
1072198092Srdivacky      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1073198092Srdivacky                                     DiagID);
1074193326Sed      break;
1075193326Sed    case tok::kw__Complex:
1076198092Srdivacky      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1077198092Srdivacky                                        DiagID);
1078193326Sed      break;
1079193326Sed    case tok::kw__Imaginary:
1080198092Srdivacky      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1081198092Srdivacky                                        DiagID);
1082193326Sed      break;
1083193326Sed    case tok::kw_void:
1084198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1085198092Srdivacky                                     DiagID);
1086193326Sed      break;
1087193326Sed    case tok::kw_char:
1088198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1089198092Srdivacky                                     DiagID);
1090193326Sed      break;
1091193326Sed    case tok::kw_int:
1092198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1093198092Srdivacky                                     DiagID);
1094193326Sed      break;
1095193326Sed    case tok::kw_float:
1096198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1097198092Srdivacky                                     DiagID);
1098193326Sed      break;
1099193326Sed    case tok::kw_double:
1100198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1101198092Srdivacky                                     DiagID);
1102193326Sed      break;
1103193326Sed    case tok::kw_wchar_t:
1104198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1105198092Srdivacky                                     DiagID);
1106193326Sed      break;
1107198092Srdivacky    case tok::kw_char16_t:
1108198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1109198092Srdivacky                                     DiagID);
1110198092Srdivacky      break;
1111198092Srdivacky    case tok::kw_char32_t:
1112198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1113198092Srdivacky                                     DiagID);
1114198092Srdivacky      break;
1115193326Sed    case tok::kw_bool:
1116193326Sed    case tok::kw__Bool:
1117198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1118198092Srdivacky                                     DiagID);
1119193326Sed      break;
1120193326Sed    case tok::kw__Decimal32:
1121198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1122198092Srdivacky                                     DiagID);
1123193326Sed      break;
1124193326Sed    case tok::kw__Decimal64:
1125198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1126198092Srdivacky                                     DiagID);
1127193326Sed      break;
1128193326Sed    case tok::kw__Decimal128:
1129198092Srdivacky      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1130198092Srdivacky                                     DiagID);
1131193326Sed      break;
1132193326Sed
1133193326Sed    // class-specifier:
1134193326Sed    case tok::kw_class:
1135193326Sed    case tok::kw_struct:
1136193326Sed    case tok::kw_union: {
1137193326Sed      tok::TokenKind Kind = Tok.getKind();
1138193326Sed      ConsumeToken();
1139193326Sed      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1140193326Sed      continue;
1141193326Sed    }
1142193326Sed
1143193326Sed    // enum-specifier:
1144193326Sed    case tok::kw_enum:
1145193326Sed      ConsumeToken();
1146193326Sed      ParseEnumSpecifier(Loc, DS, AS);
1147193326Sed      continue;
1148193326Sed
1149193326Sed    // cv-qualifier:
1150193326Sed    case tok::kw_const:
1151198092Srdivacky      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1152198092Srdivacky                                 getLang());
1153193326Sed      break;
1154193326Sed    case tok::kw_volatile:
1155198092Srdivacky      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1156198092Srdivacky                                 getLang());
1157193326Sed      break;
1158193326Sed    case tok::kw_restrict:
1159198092Srdivacky      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1160198092Srdivacky                                 getLang());
1161193326Sed      break;
1162193326Sed
1163193326Sed    // C++ typename-specifier:
1164193326Sed    case tok::kw_typename:
1165193326Sed      if (TryAnnotateTypeOrScopeToken())
1166193326Sed        continue;
1167193326Sed      break;
1168193326Sed
1169193326Sed    // GNU typeof support.
1170193326Sed    case tok::kw_typeof:
1171193326Sed      ParseTypeofSpecifier(DS);
1172193326Sed      continue;
1173193326Sed
1174195099Sed    case tok::kw_decltype:
1175195099Sed      ParseDecltypeSpecifier(DS);
1176195099Sed      continue;
1177195099Sed
1178193326Sed    case tok::less:
1179193326Sed      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1180193326Sed      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
1181193326Sed      // but we support it.
1182193326Sed      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1183193326Sed        goto DoneWithDeclSpec;
1184198092Srdivacky
1185193326Sed      {
1186198092Srdivacky        SourceLocation LAngleLoc, EndProtoLoc;
1187193326Sed        llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1188198092Srdivacky        llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1189198092Srdivacky        ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1190198092Srdivacky                                    LAngleLoc, EndProtoLoc);
1191198092Srdivacky        DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1192198092Srdivacky                                 ProtocolLocs.data(), LAngleLoc);
1193193326Sed        DS.SetRangeEnd(EndProtoLoc);
1194193326Sed
1195193326Sed        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1196193326Sed          << CodeModificationHint::CreateInsertion(Loc, "id")
1197193326Sed          << SourceRange(Loc, EndProtoLoc);
1198193326Sed        // Need to support trailing type qualifiers (e.g. "id<p> const").
1199193326Sed        // If a type specifier follows, it will be diagnosed elsewhere.
1200193326Sed        continue;
1201193326Sed      }
1202193326Sed    }
1203198092Srdivacky    // If the specifier wasn't legal, issue a diagnostic.
1204193326Sed    if (isInvalid) {
1205193326Sed      assert(PrevSpec && "Method did not return previous specifier!");
1206198092Srdivacky      assert(DiagID);
1207193326Sed      Diag(Tok, DiagID) << PrevSpec;
1208193326Sed    }
1209193326Sed    DS.SetRangeEnd(Tok.getLocation());
1210193326Sed    ConsumeToken();
1211193326Sed  }
1212193326Sed}
1213193326Sed
1214193326Sed/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1215193326Sed/// primarily follow the C++ grammar with additions for C99 and GNU,
1216193326Sed/// which together subsume the C grammar. Note that the C++
1217193326Sed/// type-specifier also includes the C type-qualifier (for const,
1218193326Sed/// volatile, and C99 restrict). Returns true if a type-specifier was
1219193326Sed/// found (and parsed), false otherwise.
1220193326Sed///
1221193326Sed///       type-specifier: [C++ 7.1.5]
1222193326Sed///         simple-type-specifier
1223193326Sed///         class-specifier
1224193326Sed///         enum-specifier
1225193326Sed///         elaborated-type-specifier  [TODO]
1226193326Sed///         cv-qualifier
1227193326Sed///
1228193326Sed///       cv-qualifier: [C++ 7.1.5.1]
1229193326Sed///         'const'
1230193326Sed///         'volatile'
1231193326Sed/// [C99]   'restrict'
1232193326Sed///
1233193326Sed///       simple-type-specifier: [ C++ 7.1.5.2]
1234193326Sed///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
1235193326Sed///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
1236193326Sed///         'char'
1237193326Sed///         'wchar_t'
1238193326Sed///         'bool'
1239193326Sed///         'short'
1240193326Sed///         'int'
1241193326Sed///         'long'
1242193326Sed///         'signed'
1243193326Sed///         'unsigned'
1244193326Sed///         'float'
1245193326Sed///         'double'
1246193326Sed///         'void'
1247193326Sed/// [C99]   '_Bool'
1248193326Sed/// [C99]   '_Complex'
1249193326Sed/// [C99]   '_Imaginary'  // Removed in TC2?
1250193326Sed/// [GNU]   '_Decimal32'
1251193326Sed/// [GNU]   '_Decimal64'
1252193326Sed/// [GNU]   '_Decimal128'
1253193326Sed/// [GNU]   typeof-specifier
1254193326Sed/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
1255193326Sed/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
1256195099Sed/// [C++0x] 'decltype' ( expression )
1257198092Srdivackybool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1258193326Sed                                        const char *&PrevSpec,
1259198092Srdivacky                                        unsigned &DiagID,
1260193326Sed                                      const ParsedTemplateInfo &TemplateInfo) {
1261193326Sed  SourceLocation Loc = Tok.getLocation();
1262193326Sed
1263193326Sed  switch (Tok.getKind()) {
1264193326Sed  case tok::identifier:   // foo::bar
1265193326Sed  case tok::kw_typename:  // typename foo::bar
1266193326Sed    // Annotate typenames and C++ scope specifiers.  If we get one, just
1267193326Sed    // recurse to handle whatever we get.
1268193326Sed    if (TryAnnotateTypeOrScopeToken())
1269198092Srdivacky      return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1270198092Srdivacky                                        TemplateInfo);
1271193326Sed    // Otherwise, not a type specifier.
1272193326Sed    return false;
1273193326Sed  case tok::coloncolon:   // ::foo::bar
1274193326Sed    if (NextToken().is(tok::kw_new) ||    // ::new
1275193326Sed        NextToken().is(tok::kw_delete))   // ::delete
1276193326Sed      return false;
1277198092Srdivacky
1278193326Sed    // Annotate typenames and C++ scope specifiers.  If we get one, just
1279193326Sed    // recurse to handle whatever we get.
1280193326Sed    if (TryAnnotateTypeOrScopeToken())
1281198092Srdivacky      return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1282198092Srdivacky                                        TemplateInfo);
1283193326Sed    // Otherwise, not a type specifier.
1284193326Sed    return false;
1285198092Srdivacky
1286193326Sed  // simple-type-specifier:
1287193326Sed  case tok::annot_typename: {
1288193326Sed    if (Tok.getAnnotationValue())
1289193326Sed      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1290198092Srdivacky                                     DiagID, Tok.getAnnotationValue());
1291193326Sed    else
1292193326Sed      DS.SetTypeSpecError();
1293193326Sed    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1294193326Sed    ConsumeToken(); // The typename
1295198092Srdivacky
1296193326Sed    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1297193326Sed    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1298193326Sed    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1299193326Sed    // just a normal reference to a typedef name.
1300193326Sed    if (!Tok.is(tok::less) || !getLang().ObjC1)
1301193326Sed      return true;
1302198092Srdivacky
1303198092Srdivacky    SourceLocation LAngleLoc, EndProtoLoc;
1304193326Sed    llvm::SmallVector<DeclPtrTy, 8> ProtocolDecl;
1305198092Srdivacky    llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1306198092Srdivacky    ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1307198092Srdivacky                                LAngleLoc, EndProtoLoc);
1308198092Srdivacky    DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1309198092Srdivacky                             ProtocolLocs.data(), LAngleLoc);
1310198092Srdivacky
1311193326Sed    DS.SetRangeEnd(EndProtoLoc);
1312193326Sed    return true;
1313193326Sed  }
1314193326Sed
1315193326Sed  case tok::kw_short:
1316198092Srdivacky    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1317193326Sed    break;
1318193326Sed  case tok::kw_long:
1319193326Sed    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1320198092Srdivacky      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1321198092Srdivacky                                      DiagID);
1322193326Sed    else
1323198092Srdivacky      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1324198092Srdivacky                                      DiagID);
1325193326Sed    break;
1326193326Sed  case tok::kw_signed:
1327198092Srdivacky    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1328193326Sed    break;
1329193326Sed  case tok::kw_unsigned:
1330198092Srdivacky    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1331198092Srdivacky                                   DiagID);
1332193326Sed    break;
1333193326Sed  case tok::kw__Complex:
1334198092Srdivacky    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1335198092Srdivacky                                      DiagID);
1336193326Sed    break;
1337193326Sed  case tok::kw__Imaginary:
1338198092Srdivacky    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1339198092Srdivacky                                      DiagID);
1340193326Sed    break;
1341193326Sed  case tok::kw_void:
1342198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1343193326Sed    break;
1344193326Sed  case tok::kw_char:
1345198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1346193326Sed    break;
1347193326Sed  case tok::kw_int:
1348198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1349193326Sed    break;
1350193326Sed  case tok::kw_float:
1351198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1352193326Sed    break;
1353193326Sed  case tok::kw_double:
1354198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1355193326Sed    break;
1356193326Sed  case tok::kw_wchar_t:
1357198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1358193326Sed    break;
1359198092Srdivacky  case tok::kw_char16_t:
1360198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1361198092Srdivacky    break;
1362198092Srdivacky  case tok::kw_char32_t:
1363198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1364198092Srdivacky    break;
1365193326Sed  case tok::kw_bool:
1366193326Sed  case tok::kw__Bool:
1367198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1368193326Sed    break;
1369193326Sed  case tok::kw__Decimal32:
1370198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1371198092Srdivacky                                   DiagID);
1372193326Sed    break;
1373193326Sed  case tok::kw__Decimal64:
1374198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1375198092Srdivacky                                   DiagID);
1376193326Sed    break;
1377193326Sed  case tok::kw__Decimal128:
1378198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1379198092Srdivacky                                   DiagID);
1380193326Sed    break;
1381193326Sed
1382193326Sed  // class-specifier:
1383193326Sed  case tok::kw_class:
1384193326Sed  case tok::kw_struct:
1385193326Sed  case tok::kw_union: {
1386193326Sed    tok::TokenKind Kind = Tok.getKind();
1387193326Sed    ConsumeToken();
1388193326Sed    ParseClassSpecifier(Kind, Loc, DS, TemplateInfo);
1389193326Sed    return true;
1390193326Sed  }
1391193326Sed
1392193326Sed  // enum-specifier:
1393193326Sed  case tok::kw_enum:
1394193326Sed    ConsumeToken();
1395193326Sed    ParseEnumSpecifier(Loc, DS);
1396193326Sed    return true;
1397193326Sed
1398193326Sed  // cv-qualifier:
1399193326Sed  case tok::kw_const:
1400193326Sed    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
1401198092Srdivacky                               DiagID, getLang());
1402193326Sed    break;
1403193326Sed  case tok::kw_volatile:
1404193326Sed    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
1405198092Srdivacky                               DiagID, getLang());
1406193326Sed    break;
1407193326Sed  case tok::kw_restrict:
1408193326Sed    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
1409198092Srdivacky                               DiagID, getLang());
1410193326Sed    break;
1411193326Sed
1412193326Sed  // GNU typeof support.
1413193326Sed  case tok::kw_typeof:
1414193326Sed    ParseTypeofSpecifier(DS);
1415193326Sed    return true;
1416193326Sed
1417195099Sed  // C++0x decltype support.
1418195099Sed  case tok::kw_decltype:
1419195099Sed    ParseDecltypeSpecifier(DS);
1420195099Sed    return true;
1421198092Srdivacky
1422195099Sed  // C++0x auto support.
1423195099Sed  case tok::kw_auto:
1424195099Sed    if (!getLang().CPlusPlus0x)
1425195099Sed      return false;
1426195099Sed
1427198092Srdivacky    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
1428195099Sed    break;
1429194179Sed  case tok::kw___ptr64:
1430194179Sed  case tok::kw___w64:
1431193326Sed  case tok::kw___cdecl:
1432193326Sed  case tok::kw___stdcall:
1433193326Sed  case tok::kw___fastcall:
1434194179Sed    DS.AddAttributes(ParseMicrosoftTypeAttributes());
1435193326Sed    return true;
1436193326Sed
1437193326Sed  default:
1438193326Sed    // Not a type-specifier; do nothing.
1439193326Sed    return false;
1440193326Sed  }
1441193326Sed
1442193326Sed  // If the specifier combination wasn't legal, issue a diagnostic.
1443193326Sed  if (isInvalid) {
1444193326Sed    assert(PrevSpec && "Method did not return previous specifier!");
1445193326Sed    // Pick between error or extwarn.
1446193326Sed    Diag(Tok, DiagID) << PrevSpec;
1447193326Sed  }
1448193326Sed  DS.SetRangeEnd(Tok.getLocation());
1449193326Sed  ConsumeToken(); // whatever we parsed above.
1450193326Sed  return true;
1451193326Sed}
1452193326Sed
1453193326Sed/// ParseStructDeclaration - Parse a struct declaration without the terminating
1454193326Sed/// semicolon.
1455193326Sed///
1456193326Sed///       struct-declaration:
1457193326Sed///         specifier-qualifier-list struct-declarator-list
1458193326Sed/// [GNU]   __extension__ struct-declaration
1459193326Sed/// [GNU]   specifier-qualifier-list
1460193326Sed///       struct-declarator-list:
1461193326Sed///         struct-declarator
1462193326Sed///         struct-declarator-list ',' struct-declarator
1463193326Sed/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
1464193326Sed///       struct-declarator:
1465193326Sed///         declarator
1466193326Sed/// [GNU]   declarator attributes[opt]
1467193326Sed///         declarator[opt] ':' constant-expression
1468193326Sed/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
1469193326Sed///
1470193326Sedvoid Parser::
1471193326SedParseStructDeclaration(DeclSpec &DS,
1472193326Sed                       llvm::SmallVectorImpl<FieldDeclarator> &Fields) {
1473193326Sed  if (Tok.is(tok::kw___extension__)) {
1474193326Sed    // __extension__ silences extension warnings in the subexpression.
1475193326Sed    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1476193326Sed    ConsumeToken();
1477193326Sed    return ParseStructDeclaration(DS, Fields);
1478193326Sed  }
1479198092Srdivacky
1480193326Sed  // Parse the common specifier-qualifiers-list piece.
1481193326Sed  SourceLocation DSStart = Tok.getLocation();
1482193326Sed  ParseSpecifierQualifierList(DS);
1483198092Srdivacky
1484193326Sed  // If there are no declarators, this is a free-standing declaration
1485193326Sed  // specifier. Let the actions module cope with it.
1486193326Sed  if (Tok.is(tok::semi)) {
1487193326Sed    Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1488193326Sed    return;
1489193326Sed  }
1490193326Sed
1491193326Sed  // Read struct-declarators until we find the semicolon.
1492193326Sed  Fields.push_back(FieldDeclarator(DS));
1493193326Sed  while (1) {
1494193326Sed    FieldDeclarator &DeclaratorInfo = Fields.back();
1495198092Srdivacky
1496193326Sed    /// struct-declarator: declarator
1497193326Sed    /// struct-declarator: declarator[opt] ':' constant-expression
1498193326Sed    if (Tok.isNot(tok::colon))
1499193326Sed      ParseDeclarator(DeclaratorInfo.D);
1500198092Srdivacky
1501193326Sed    if (Tok.is(tok::colon)) {
1502193326Sed      ConsumeToken();
1503193326Sed      OwningExprResult Res(ParseConstantExpression());
1504193326Sed      if (Res.isInvalid())
1505193326Sed        SkipUntil(tok::semi, true, true);
1506193326Sed      else
1507193326Sed        DeclaratorInfo.BitfieldSize = Res.release();
1508193326Sed    }
1509193326Sed
1510193326Sed    // If attributes exist after the declarator, parse them.
1511193326Sed    if (Tok.is(tok::kw___attribute)) {
1512193326Sed      SourceLocation Loc;
1513193326Sed      AttributeList *AttrList = ParseAttributes(&Loc);
1514193326Sed      DeclaratorInfo.D.AddAttributes(AttrList, Loc);
1515193326Sed    }
1516193326Sed
1517193326Sed    // If we don't have a comma, it is either the end of the list (a ';')
1518193326Sed    // or an error, bail out.
1519193326Sed    if (Tok.isNot(tok::comma))
1520193326Sed      return;
1521193326Sed
1522193326Sed    // Consume the comma.
1523193326Sed    ConsumeToken();
1524193326Sed
1525193326Sed    // Parse the next declarator.
1526193326Sed    Fields.push_back(FieldDeclarator(DS));
1527193326Sed
1528193326Sed    // Attributes are only allowed on the second declarator.
1529193326Sed    if (Tok.is(tok::kw___attribute)) {
1530193326Sed      SourceLocation Loc;
1531193326Sed      AttributeList *AttrList = ParseAttributes(&Loc);
1532193326Sed      Fields.back().D.AddAttributes(AttrList, Loc);
1533193326Sed    }
1534193326Sed  }
1535193326Sed}
1536193326Sed
1537193326Sed/// ParseStructUnionBody
1538193326Sed///       struct-contents:
1539193326Sed///         struct-declaration-list
1540193326Sed/// [EXT]   empty
1541193326Sed/// [GNU]   "struct-declaration-list" without terminatoring ';'
1542193326Sed///       struct-declaration-list:
1543193326Sed///         struct-declaration
1544193326Sed///         struct-declaration-list struct-declaration
1545193326Sed/// [OBC]   '@' 'defs' '(' class-name ')'
1546193326Sed///
1547193326Sedvoid Parser::ParseStructUnionBody(SourceLocation RecordLoc,
1548193326Sed                                  unsigned TagType, DeclPtrTy TagDecl) {
1549193326Sed  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1550193326Sed                                        PP.getSourceManager(),
1551193326Sed                                        "parsing struct/union body");
1552198092Srdivacky
1553193326Sed  SourceLocation LBraceLoc = ConsumeBrace();
1554198092Srdivacky
1555193326Sed  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
1556193326Sed  Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1557193326Sed
1558193326Sed  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
1559193326Sed  // C++.
1560193326Sed  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1561193326Sed    Diag(Tok, diag::ext_empty_struct_union_enum)
1562193326Sed      << DeclSpec::getSpecifierName((DeclSpec::TST)TagType);
1563193326Sed
1564193326Sed  llvm::SmallVector<DeclPtrTy, 32> FieldDecls;
1565193326Sed  llvm::SmallVector<FieldDeclarator, 8> FieldDeclarators;
1566193326Sed
1567193326Sed  // While we still have something to read, read the declarations in the struct.
1568193326Sed  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1569193326Sed    // Each iteration of this loop reads one struct-declaration.
1570198092Srdivacky
1571193326Sed    // Check for extraneous top-level semicolon.
1572193326Sed    if (Tok.is(tok::semi)) {
1573193326Sed      Diag(Tok, diag::ext_extra_struct_semi)
1574193326Sed        << CodeModificationHint::CreateRemoval(SourceRange(Tok.getLocation()));
1575193326Sed      ConsumeToken();
1576193326Sed      continue;
1577193326Sed    }
1578193326Sed
1579193326Sed    // Parse all the comma separated declarators.
1580193326Sed    DeclSpec DS;
1581193326Sed    FieldDeclarators.clear();
1582193326Sed    if (!Tok.is(tok::at)) {
1583193326Sed      ParseStructDeclaration(DS, FieldDeclarators);
1584198092Srdivacky
1585193326Sed      // Convert them all to fields.
1586193326Sed      for (unsigned i = 0, e = FieldDeclarators.size(); i != e; ++i) {
1587193326Sed        FieldDeclarator &FD = FieldDeclarators[i];
1588198092Srdivacky        DeclPtrTy Field;
1589193326Sed        // Install the declarator into the current TagDecl.
1590198092Srdivacky        if (FD.D.getExtension()) {
1591198092Srdivacky          // Silences extension warnings
1592198092Srdivacky          ExtensionRAIIObject O(Diags);
1593198092Srdivacky          Field = Actions.ActOnField(CurScope, TagDecl,
1594198092Srdivacky                                     DS.getSourceRange().getBegin(),
1595198092Srdivacky                                     FD.D, FD.BitfieldSize);
1596198092Srdivacky        } else {
1597198092Srdivacky          Field = Actions.ActOnField(CurScope, TagDecl,
1598198092Srdivacky                                     DS.getSourceRange().getBegin(),
1599198092Srdivacky                                     FD.D, FD.BitfieldSize);
1600198092Srdivacky        }
1601193326Sed        FieldDecls.push_back(Field);
1602193326Sed      }
1603193326Sed    } else { // Handle @defs
1604193326Sed      ConsumeToken();
1605193326Sed      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
1606193326Sed        Diag(Tok, diag::err_unexpected_at);
1607193326Sed        SkipUntil(tok::semi, true, true);
1608193326Sed        continue;
1609193326Sed      }
1610193326Sed      ConsumeToken();
1611193326Sed      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
1612193326Sed      if (!Tok.is(tok::identifier)) {
1613193326Sed        Diag(Tok, diag::err_expected_ident);
1614193326Sed        SkipUntil(tok::semi, true, true);
1615193326Sed        continue;
1616193326Sed      }
1617193326Sed      llvm::SmallVector<DeclPtrTy, 16> Fields;
1618198092Srdivacky      Actions.ActOnDefs(CurScope, TagDecl, Tok.getLocation(),
1619193326Sed                        Tok.getIdentifierInfo(), Fields);
1620193326Sed      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
1621193326Sed      ConsumeToken();
1622193326Sed      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
1623198092Srdivacky    }
1624193326Sed
1625193326Sed    if (Tok.is(tok::semi)) {
1626193326Sed      ConsumeToken();
1627193326Sed    } else if (Tok.is(tok::r_brace)) {
1628193326Sed      Diag(Tok, diag::ext_expected_semi_decl_list);
1629193326Sed      break;
1630193326Sed    } else {
1631193326Sed      Diag(Tok, diag::err_expected_semi_decl_list);
1632193326Sed      // Skip to end of block or statement
1633193326Sed      SkipUntil(tok::r_brace, true, true);
1634193326Sed    }
1635193326Sed  }
1636198092Srdivacky
1637193326Sed  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1638198092Srdivacky
1639193326Sed  AttributeList *AttrList = 0;
1640193326Sed  // If attributes exist after struct contents, parse them.
1641193326Sed  if (Tok.is(tok::kw___attribute))
1642193326Sed    AttrList = ParseAttributes();
1643193326Sed
1644193326Sed  Actions.ActOnFields(CurScope,
1645193326Sed                      RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
1646193326Sed                      LBraceLoc, RBraceLoc,
1647193326Sed                      AttrList);
1648193326Sed  StructScope.Exit();
1649198092Srdivacky  Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1650193326Sed}
1651193326Sed
1652193326Sed
1653193326Sed/// ParseEnumSpecifier
1654193326Sed///       enum-specifier: [C99 6.7.2.2]
1655193326Sed///         'enum' identifier[opt] '{' enumerator-list '}'
1656193326Sed///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
1657193326Sed/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
1658193326Sed///                                                 '}' attributes[opt]
1659193326Sed///         'enum' identifier
1660193326Sed/// [GNU]   'enum' attributes[opt] identifier
1661193326Sed///
1662193326Sed/// [C++] elaborated-type-specifier:
1663193326Sed/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
1664193326Sed///
1665193326Sedvoid Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
1666193326Sed                                AccessSpecifier AS) {
1667193326Sed  // Parse the tag portion of this.
1668198092Srdivacky  if (Tok.is(tok::code_completion)) {
1669198092Srdivacky    // Code completion for an enum name.
1670198092Srdivacky    Actions.CodeCompleteTag(CurScope, DeclSpec::TST_enum);
1671198092Srdivacky    ConsumeToken();
1672198092Srdivacky  }
1673198092Srdivacky
1674193326Sed  AttributeList *Attr = 0;
1675193326Sed  // If attributes exist after tag, parse them.
1676193326Sed  if (Tok.is(tok::kw___attribute))
1677193326Sed    Attr = ParseAttributes();
1678193326Sed
1679193326Sed  CXXScopeSpec SS;
1680198092Srdivacky  if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS, 0, false)) {
1681193326Sed    if (Tok.isNot(tok::identifier)) {
1682193326Sed      Diag(Tok, diag::err_expected_ident);
1683193326Sed      if (Tok.isNot(tok::l_brace)) {
1684193326Sed        // Has no name and is not a definition.
1685193326Sed        // Skip the rest of this declarator, up until the comma or semicolon.
1686193326Sed        SkipUntil(tok::comma, true);
1687193326Sed        return;
1688193326Sed      }
1689193326Sed    }
1690193326Sed  }
1691198092Srdivacky
1692193326Sed  // Must have either 'enum name' or 'enum {...}'.
1693193326Sed  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace)) {
1694193326Sed    Diag(Tok, diag::err_expected_ident_lbrace);
1695198092Srdivacky
1696193326Sed    // Skip the rest of this declarator, up until the comma or semicolon.
1697193326Sed    SkipUntil(tok::comma, true);
1698193326Sed    return;
1699193326Sed  }
1700198092Srdivacky
1701193326Sed  // If an identifier is present, consume and remember it.
1702193326Sed  IdentifierInfo *Name = 0;
1703193326Sed  SourceLocation NameLoc;
1704193326Sed  if (Tok.is(tok::identifier)) {
1705193326Sed    Name = Tok.getIdentifierInfo();
1706193326Sed    NameLoc = ConsumeToken();
1707193326Sed  }
1708198092Srdivacky
1709193326Sed  // There are three options here.  If we have 'enum foo;', then this is a
1710193326Sed  // forward declaration.  If we have 'enum foo {...' then this is a
1711193326Sed  // definition. Otherwise we have something like 'enum foo xyz', a reference.
1712193326Sed  //
1713193326Sed  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
1714193326Sed  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
1715193326Sed  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
1716193326Sed  //
1717198092Srdivacky  Action::TagUseKind TUK;
1718193326Sed  if (Tok.is(tok::l_brace))
1719198092Srdivacky    TUK = Action::TUK_Definition;
1720193326Sed  else if (Tok.is(tok::semi))
1721198092Srdivacky    TUK = Action::TUK_Declaration;
1722193326Sed  else
1723198092Srdivacky    TUK = Action::TUK_Reference;
1724193326Sed  bool Owned = false;
1725198092Srdivacky  bool IsDependent = false;
1726198092Srdivacky  DeclPtrTy TagDecl = Actions.ActOnTag(CurScope, DeclSpec::TST_enum, TUK,
1727193326Sed                                       StartLoc, SS, Name, NameLoc, Attr, AS,
1728198092Srdivacky                                       Action::MultiTemplateParamsArg(Actions),
1729198092Srdivacky                                       Owned, IsDependent);
1730198092Srdivacky  assert(!IsDependent && "didn't expect dependent enum");
1731198092Srdivacky
1732193326Sed  if (Tok.is(tok::l_brace))
1733193326Sed    ParseEnumBody(StartLoc, TagDecl);
1734198092Srdivacky
1735193326Sed  // TODO: semantic analysis on the declspec for enums.
1736193326Sed  const char *PrevSpec = 0;
1737198092Srdivacky  unsigned DiagID;
1738198092Srdivacky  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, PrevSpec, DiagID,
1739193326Sed                         TagDecl.getAs<void>(), Owned))
1740198092Srdivacky    Diag(StartLoc, DiagID) << PrevSpec;
1741193326Sed}
1742193326Sed
1743193326Sed/// ParseEnumBody - Parse a {} enclosed enumerator-list.
1744193326Sed///       enumerator-list:
1745193326Sed///         enumerator
1746193326Sed///         enumerator-list ',' enumerator
1747193326Sed///       enumerator:
1748193326Sed///         enumeration-constant
1749193326Sed///         enumeration-constant '=' constant-expression
1750193326Sed///       enumeration-constant:
1751193326Sed///         identifier
1752193326Sed///
1753193326Sedvoid Parser::ParseEnumBody(SourceLocation StartLoc, DeclPtrTy EnumDecl) {
1754193326Sed  // Enter the scope of the enum body and start the definition.
1755193326Sed  ParseScope EnumScope(this, Scope::DeclScope);
1756193326Sed  Actions.ActOnTagStartDefinition(CurScope, EnumDecl);
1757193326Sed
1758193326Sed  SourceLocation LBraceLoc = ConsumeBrace();
1759198092Srdivacky
1760193326Sed  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
1761193326Sed  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
1762193326Sed    Diag(Tok, diag::ext_empty_struct_union_enum) << "enum";
1763198092Srdivacky
1764193326Sed  llvm::SmallVector<DeclPtrTy, 32> EnumConstantDecls;
1765193326Sed
1766193326Sed  DeclPtrTy LastEnumConstDecl;
1767198092Srdivacky
1768193326Sed  // Parse the enumerator-list.
1769193326Sed  while (Tok.is(tok::identifier)) {
1770193326Sed    IdentifierInfo *Ident = Tok.getIdentifierInfo();
1771193326Sed    SourceLocation IdentLoc = ConsumeToken();
1772198092Srdivacky
1773193326Sed    SourceLocation EqualLoc;
1774193326Sed    OwningExprResult AssignedVal(Actions);
1775193326Sed    if (Tok.is(tok::equal)) {
1776193326Sed      EqualLoc = ConsumeToken();
1777193326Sed      AssignedVal = ParseConstantExpression();
1778193326Sed      if (AssignedVal.isInvalid())
1779193326Sed        SkipUntil(tok::comma, tok::r_brace, true, true);
1780193326Sed    }
1781198092Srdivacky
1782193326Sed    // Install the enumerator constant into EnumDecl.
1783193326Sed    DeclPtrTy EnumConstDecl = Actions.ActOnEnumConstant(CurScope, EnumDecl,
1784193326Sed                                                        LastEnumConstDecl,
1785193326Sed                                                        IdentLoc, Ident,
1786193326Sed                                                        EqualLoc,
1787193326Sed                                                        AssignedVal.release());
1788193326Sed    EnumConstantDecls.push_back(EnumConstDecl);
1789193326Sed    LastEnumConstDecl = EnumConstDecl;
1790198092Srdivacky
1791193326Sed    if (Tok.isNot(tok::comma))
1792193326Sed      break;
1793193326Sed    SourceLocation CommaLoc = ConsumeToken();
1794198092Srdivacky
1795198092Srdivacky    if (Tok.isNot(tok::identifier) &&
1796193326Sed        !(getLang().C99 || getLang().CPlusPlus0x))
1797193326Sed      Diag(CommaLoc, diag::ext_enumerator_list_comma)
1798193326Sed        << getLang().CPlusPlus
1799193326Sed        << CodeModificationHint::CreateRemoval((SourceRange(CommaLoc)));
1800193326Sed  }
1801198092Srdivacky
1802193326Sed  // Eat the }.
1803193326Sed  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1804193326Sed
1805198092Srdivacky  AttributeList *Attr = 0;
1806193326Sed  // If attributes exist after the identifier list, parse them.
1807193326Sed  if (Tok.is(tok::kw___attribute))
1808198092Srdivacky    Attr = ParseAttributes();
1809193326Sed
1810198092Srdivacky  Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
1811198092Srdivacky                        EnumConstantDecls.data(), EnumConstantDecls.size(),
1812198092Srdivacky                        CurScope, Attr);
1813198092Srdivacky
1814193326Sed  EnumScope.Exit();
1815198092Srdivacky  Actions.ActOnTagFinishDefinition(CurScope, EnumDecl, RBraceLoc);
1816193326Sed}
1817193326Sed
1818193326Sed/// isTypeSpecifierQualifier - Return true if the current token could be the
1819193326Sed/// start of a type-qualifier-list.
1820193326Sedbool Parser::isTypeQualifier() const {
1821193326Sed  switch (Tok.getKind()) {
1822193326Sed  default: return false;
1823193326Sed    // type-qualifier
1824193326Sed  case tok::kw_const:
1825193326Sed  case tok::kw_volatile:
1826193326Sed  case tok::kw_restrict:
1827193326Sed    return true;
1828193326Sed  }
1829193326Sed}
1830193326Sed
1831193326Sed/// isTypeSpecifierQualifier - Return true if the current token could be the
1832193326Sed/// start of a specifier-qualifier-list.
1833193326Sedbool Parser::isTypeSpecifierQualifier() {
1834193326Sed  switch (Tok.getKind()) {
1835193326Sed  default: return false;
1836198092Srdivacky
1837193326Sed  case tok::identifier:   // foo::bar
1838193326Sed  case tok::kw_typename:  // typename T::type
1839193326Sed    // Annotate typenames and C++ scope specifiers.  If we get one, just
1840193326Sed    // recurse to handle whatever we get.
1841193326Sed    if (TryAnnotateTypeOrScopeToken())
1842193326Sed      return isTypeSpecifierQualifier();
1843193326Sed    // Otherwise, not a type specifier.
1844193326Sed    return false;
1845193326Sed
1846193326Sed  case tok::coloncolon:   // ::foo::bar
1847193326Sed    if (NextToken().is(tok::kw_new) ||    // ::new
1848193326Sed        NextToken().is(tok::kw_delete))   // ::delete
1849193326Sed      return false;
1850193326Sed
1851193326Sed    // Annotate typenames and C++ scope specifiers.  If we get one, just
1852193326Sed    // recurse to handle whatever we get.
1853193326Sed    if (TryAnnotateTypeOrScopeToken())
1854193326Sed      return isTypeSpecifierQualifier();
1855193326Sed    // Otherwise, not a type specifier.
1856193326Sed    return false;
1857198092Srdivacky
1858193326Sed    // GNU attributes support.
1859193326Sed  case tok::kw___attribute:
1860193326Sed    // GNU typeof support.
1861193326Sed  case tok::kw_typeof:
1862198092Srdivacky
1863193326Sed    // type-specifiers
1864193326Sed  case tok::kw_short:
1865193326Sed  case tok::kw_long:
1866193326Sed  case tok::kw_signed:
1867193326Sed  case tok::kw_unsigned:
1868193326Sed  case tok::kw__Complex:
1869193326Sed  case tok::kw__Imaginary:
1870193326Sed  case tok::kw_void:
1871193326Sed  case tok::kw_char:
1872193326Sed  case tok::kw_wchar_t:
1873198092Srdivacky  case tok::kw_char16_t:
1874198092Srdivacky  case tok::kw_char32_t:
1875193326Sed  case tok::kw_int:
1876193326Sed  case tok::kw_float:
1877193326Sed  case tok::kw_double:
1878193326Sed  case tok::kw_bool:
1879193326Sed  case tok::kw__Bool:
1880193326Sed  case tok::kw__Decimal32:
1881193326Sed  case tok::kw__Decimal64:
1882193326Sed  case tok::kw__Decimal128:
1883198092Srdivacky
1884193326Sed    // struct-or-union-specifier (C99) or class-specifier (C++)
1885193326Sed  case tok::kw_class:
1886193326Sed  case tok::kw_struct:
1887193326Sed  case tok::kw_union:
1888193326Sed    // enum-specifier
1889193326Sed  case tok::kw_enum:
1890198092Srdivacky
1891193326Sed    // type-qualifier
1892193326Sed  case tok::kw_const:
1893193326Sed  case tok::kw_volatile:
1894193326Sed  case tok::kw_restrict:
1895193326Sed
1896193326Sed    // typedef-name
1897193326Sed  case tok::annot_typename:
1898193326Sed    return true;
1899198092Srdivacky
1900193326Sed    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
1901193326Sed  case tok::less:
1902193326Sed    return getLang().ObjC1;
1903198092Srdivacky
1904193326Sed  case tok::kw___cdecl:
1905193326Sed  case tok::kw___stdcall:
1906193326Sed  case tok::kw___fastcall:
1907194179Sed  case tok::kw___w64:
1908194179Sed  case tok::kw___ptr64:
1909194179Sed    return true;
1910193326Sed  }
1911193326Sed}
1912193326Sed
1913193326Sed/// isDeclarationSpecifier() - Return true if the current token is part of a
1914193326Sed/// declaration specifier.
1915193326Sedbool Parser::isDeclarationSpecifier() {
1916193326Sed  switch (Tok.getKind()) {
1917193326Sed  default: return false;
1918198092Srdivacky
1919193326Sed  case tok::identifier:   // foo::bar
1920193326Sed    // Unfortunate hack to support "Class.factoryMethod" notation.
1921193326Sed    if (getLang().ObjC1 && NextToken().is(tok::period))
1922193326Sed      return false;
1923193326Sed    // Fall through
1924193326Sed
1925193326Sed  case tok::kw_typename: // typename T::type
1926193326Sed    // Annotate typenames and C++ scope specifiers.  If we get one, just
1927193326Sed    // recurse to handle whatever we get.
1928193326Sed    if (TryAnnotateTypeOrScopeToken())
1929193326Sed      return isDeclarationSpecifier();
1930193326Sed    // Otherwise, not a declaration specifier.
1931193326Sed    return false;
1932193326Sed  case tok::coloncolon:   // ::foo::bar
1933193326Sed    if (NextToken().is(tok::kw_new) ||    // ::new
1934193326Sed        NextToken().is(tok::kw_delete))   // ::delete
1935193326Sed      return false;
1936198092Srdivacky
1937193326Sed    // Annotate typenames and C++ scope specifiers.  If we get one, just
1938193326Sed    // recurse to handle whatever we get.
1939193326Sed    if (TryAnnotateTypeOrScopeToken())
1940193326Sed      return isDeclarationSpecifier();
1941193326Sed    // Otherwise, not a declaration specifier.
1942193326Sed    return false;
1943198092Srdivacky
1944193326Sed    // storage-class-specifier
1945193326Sed  case tok::kw_typedef:
1946193326Sed  case tok::kw_extern:
1947193326Sed  case tok::kw___private_extern__:
1948193326Sed  case tok::kw_static:
1949193326Sed  case tok::kw_auto:
1950193326Sed  case tok::kw_register:
1951193326Sed  case tok::kw___thread:
1952198092Srdivacky
1953193326Sed    // type-specifiers
1954193326Sed  case tok::kw_short:
1955193326Sed  case tok::kw_long:
1956193326Sed  case tok::kw_signed:
1957193326Sed  case tok::kw_unsigned:
1958193326Sed  case tok::kw__Complex:
1959193326Sed  case tok::kw__Imaginary:
1960193326Sed  case tok::kw_void:
1961193326Sed  case tok::kw_char:
1962193326Sed  case tok::kw_wchar_t:
1963198092Srdivacky  case tok::kw_char16_t:
1964198092Srdivacky  case tok::kw_char32_t:
1965198092Srdivacky
1966193326Sed  case tok::kw_int:
1967193326Sed  case tok::kw_float:
1968193326Sed  case tok::kw_double:
1969193326Sed  case tok::kw_bool:
1970193326Sed  case tok::kw__Bool:
1971193326Sed  case tok::kw__Decimal32:
1972193326Sed  case tok::kw__Decimal64:
1973193326Sed  case tok::kw__Decimal128:
1974198092Srdivacky
1975193326Sed    // struct-or-union-specifier (C99) or class-specifier (C++)
1976193326Sed  case tok::kw_class:
1977193326Sed  case tok::kw_struct:
1978193326Sed  case tok::kw_union:
1979193326Sed    // enum-specifier
1980193326Sed  case tok::kw_enum:
1981198092Srdivacky
1982193326Sed    // type-qualifier
1983193326Sed  case tok::kw_const:
1984193326Sed  case tok::kw_volatile:
1985193326Sed  case tok::kw_restrict:
1986193326Sed
1987193326Sed    // function-specifier
1988193326Sed  case tok::kw_inline:
1989193326Sed  case tok::kw_virtual:
1990193326Sed  case tok::kw_explicit:
1991193326Sed
1992193326Sed    // typedef-name
1993193326Sed  case tok::annot_typename:
1994193326Sed
1995193326Sed    // GNU typeof support.
1996193326Sed  case tok::kw_typeof:
1997198092Srdivacky
1998193326Sed    // GNU attributes.
1999193326Sed  case tok::kw___attribute:
2000193326Sed    return true;
2001198092Srdivacky
2002193326Sed    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2003193326Sed  case tok::less:
2004193326Sed    return getLang().ObjC1;
2005198092Srdivacky
2006193326Sed  case tok::kw___declspec:
2007193326Sed  case tok::kw___cdecl:
2008193326Sed  case tok::kw___stdcall:
2009193326Sed  case tok::kw___fastcall:
2010194179Sed  case tok::kw___w64:
2011194179Sed  case tok::kw___ptr64:
2012194179Sed  case tok::kw___forceinline:
2013194179Sed    return true;
2014193326Sed  }
2015193326Sed}
2016193326Sed
2017193326Sed
2018193326Sed/// ParseTypeQualifierListOpt
2019193326Sed///       type-qualifier-list: [C99 6.7.5]
2020193326Sed///         type-qualifier
2021193326Sed/// [GNU]   attributes                        [ only if AttributesAllowed=true ]
2022193326Sed///         type-qualifier-list type-qualifier
2023193326Sed/// [GNU]   type-qualifier-list attributes    [ only if AttributesAllowed=true ]
2024193326Sed///
2025193326Sedvoid Parser::ParseTypeQualifierListOpt(DeclSpec &DS, bool AttributesAllowed) {
2026193326Sed  while (1) {
2027198092Srdivacky    bool isInvalid = false;
2028193326Sed    const char *PrevSpec = 0;
2029198092Srdivacky    unsigned DiagID = 0;
2030193326Sed    SourceLocation Loc = Tok.getLocation();
2031193326Sed
2032193326Sed    switch (Tok.getKind()) {
2033193326Sed    case tok::kw_const:
2034198092Srdivacky      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
2035198092Srdivacky                                 getLang());
2036193326Sed      break;
2037193326Sed    case tok::kw_volatile:
2038198092Srdivacky      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
2039198092Srdivacky                                 getLang());
2040193326Sed      break;
2041193326Sed    case tok::kw_restrict:
2042198092Srdivacky      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
2043198092Srdivacky                                 getLang());
2044193326Sed      break;
2045194179Sed    case tok::kw___w64:
2046193326Sed    case tok::kw___ptr64:
2047193326Sed    case tok::kw___cdecl:
2048193326Sed    case tok::kw___stdcall:
2049193326Sed    case tok::kw___fastcall:
2050194179Sed      if (AttributesAllowed) {
2051194179Sed        DS.AddAttributes(ParseMicrosoftTypeAttributes());
2052194179Sed        continue;
2053194179Sed      }
2054194179Sed      goto DoneWithTypeQuals;
2055193326Sed    case tok::kw___attribute:
2056193326Sed      if (AttributesAllowed) {
2057193326Sed        DS.AddAttributes(ParseAttributes());
2058193326Sed        continue; // do *not* consume the next token!
2059193326Sed      }
2060193326Sed      // otherwise, FALL THROUGH!
2061193326Sed    default:
2062193326Sed      DoneWithTypeQuals:
2063193326Sed      // If this is not a type-qualifier token, we're done reading type
2064193326Sed      // qualifiers.  First verify that DeclSpec's are consistent.
2065193326Sed      DS.Finish(Diags, PP);
2066193326Sed      return;
2067193326Sed    }
2068193326Sed
2069193326Sed    // If the specifier combination wasn't legal, issue a diagnostic.
2070193326Sed    if (isInvalid) {
2071193326Sed      assert(PrevSpec && "Method did not return previous specifier!");
2072193326Sed      Diag(Tok, DiagID) << PrevSpec;
2073193326Sed    }
2074193326Sed    ConsumeToken();
2075193326Sed  }
2076193326Sed}
2077193326Sed
2078193326Sed
2079193326Sed/// ParseDeclarator - Parse and verify a newly-initialized declarator.
2080193326Sed///
2081193326Sedvoid Parser::ParseDeclarator(Declarator &D) {
2082193326Sed  /// This implements the 'declarator' production in the C grammar, then checks
2083193326Sed  /// for well-formedness and issues diagnostics.
2084193326Sed  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2085193326Sed}
2086193326Sed
2087193326Sed/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
2088193326Sed/// is parsed by the function passed to it. Pass null, and the direct-declarator
2089193326Sed/// isn't parsed at all, making this function effectively parse the C++
2090193326Sed/// ptr-operator production.
2091193326Sed///
2092193326Sed///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
2093193326Sed/// [C]     pointer[opt] direct-declarator
2094193326Sed/// [C++]   direct-declarator
2095193326Sed/// [C++]   ptr-operator declarator
2096193326Sed///
2097193326Sed///       pointer: [C99 6.7.5]
2098193326Sed///         '*' type-qualifier-list[opt]
2099193326Sed///         '*' type-qualifier-list[opt] pointer
2100193326Sed///
2101193326Sed///       ptr-operator:
2102193326Sed///         '*' cv-qualifier-seq[opt]
2103193326Sed///         '&'
2104193326Sed/// [C++0x] '&&'
2105193326Sed/// [GNU]   '&' restrict[opt] attributes[opt]
2106193326Sed/// [GNU?]  '&&' restrict[opt] attributes[opt]
2107193326Sed///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
2108193326Sedvoid Parser::ParseDeclaratorInternal(Declarator &D,
2109193326Sed                                     DirectDeclParseFunction DirectDeclParser) {
2110193326Sed
2111198092Srdivacky  if (Diags.hasAllExtensionsSilenced())
2112198092Srdivacky    D.setExtension();
2113193326Sed  // C++ member pointers start with a '::' or a nested-name.
2114193326Sed  // Member pointers get special handling, since there's no place for the
2115193326Sed  // scope spec in the generic path below.
2116193326Sed  if (getLang().CPlusPlus &&
2117193326Sed      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
2118193326Sed       Tok.is(tok::annot_cxxscope))) {
2119193326Sed    CXXScopeSpec SS;
2120198092Srdivacky    if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true)) {
2121198092Srdivacky      if (Tok.isNot(tok::star)) {
2122193326Sed        // The scope spec really belongs to the direct-declarator.
2123193326Sed        D.getCXXScopeSpec() = SS;
2124193326Sed        if (DirectDeclParser)
2125193326Sed          (this->*DirectDeclParser)(D);
2126193326Sed        return;
2127193326Sed      }
2128193326Sed
2129193326Sed      SourceLocation Loc = ConsumeToken();
2130193326Sed      D.SetRangeEnd(Loc);
2131193326Sed      DeclSpec DS;
2132193326Sed      ParseTypeQualifierListOpt(DS);
2133193326Sed      D.ExtendWithDeclSpec(DS);
2134193326Sed
2135193326Sed      // Recurse to parse whatever is left.
2136193326Sed      ParseDeclaratorInternal(D, DirectDeclParser);
2137193326Sed
2138193326Sed      // Sema will have to catch (syntactically invalid) pointers into global
2139193326Sed      // scope. It has to catch pointers into namespace scope anyway.
2140193326Sed      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
2141193326Sed                                                      Loc, DS.TakeAttributes()),
2142193326Sed                    /* Don't replace range end. */SourceLocation());
2143193326Sed      return;
2144193326Sed    }
2145193326Sed  }
2146193326Sed
2147193326Sed  tok::TokenKind Kind = Tok.getKind();
2148193326Sed  // Not a pointer, C++ reference, or block.
2149193326Sed  if (Kind != tok::star && Kind != tok::caret &&
2150193326Sed      (Kind != tok::amp || !getLang().CPlusPlus) &&
2151193326Sed      // We parse rvalue refs in C++03, because otherwise the errors are scary.
2152193326Sed      (Kind != tok::ampamp || !getLang().CPlusPlus)) {
2153193326Sed    if (DirectDeclParser)
2154193326Sed      (this->*DirectDeclParser)(D);
2155193326Sed    return;
2156193326Sed  }
2157193326Sed
2158193326Sed  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
2159193326Sed  // '&&' -> rvalue reference
2160193326Sed  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
2161193326Sed  D.SetRangeEnd(Loc);
2162193326Sed
2163193326Sed  if (Kind == tok::star || Kind == tok::caret) {
2164193326Sed    // Is a pointer.
2165193326Sed    DeclSpec DS;
2166193326Sed
2167193326Sed    ParseTypeQualifierListOpt(DS);
2168193326Sed    D.ExtendWithDeclSpec(DS);
2169193326Sed
2170193326Sed    // Recursively parse the declarator.
2171193326Sed    ParseDeclaratorInternal(D, DirectDeclParser);
2172193326Sed    if (Kind == tok::star)
2173193326Sed      // Remember that we parsed a pointer type, and remember the type-quals.
2174193326Sed      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
2175193326Sed                                                DS.TakeAttributes()),
2176193326Sed                    SourceLocation());
2177193326Sed    else
2178193326Sed      // Remember that we parsed a Block type, and remember the type-quals.
2179198092Srdivacky      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
2180193326Sed                                                     Loc, DS.TakeAttributes()),
2181193326Sed                    SourceLocation());
2182193326Sed  } else {
2183193326Sed    // Is a reference
2184193326Sed    DeclSpec DS;
2185193326Sed
2186193326Sed    // Complain about rvalue references in C++03, but then go on and build
2187193326Sed    // the declarator.
2188193326Sed    if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
2189193326Sed      Diag(Loc, diag::err_rvalue_reference);
2190193326Sed
2191193326Sed    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
2192193326Sed    // cv-qualifiers are introduced through the use of a typedef or of a
2193193326Sed    // template type argument, in which case the cv-qualifiers are ignored.
2194193326Sed    //
2195193326Sed    // [GNU] Retricted references are allowed.
2196193326Sed    // [GNU] Attributes on references are allowed.
2197193326Sed    ParseTypeQualifierListOpt(DS);
2198193326Sed    D.ExtendWithDeclSpec(DS);
2199193326Sed
2200193326Sed    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2201193326Sed      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2202193326Sed        Diag(DS.getConstSpecLoc(),
2203193326Sed             diag::err_invalid_reference_qualifier_application) << "const";
2204193326Sed      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2205193326Sed        Diag(DS.getVolatileSpecLoc(),
2206193326Sed             diag::err_invalid_reference_qualifier_application) << "volatile";
2207193326Sed    }
2208193326Sed
2209193326Sed    // Recursively parse the declarator.
2210193326Sed    ParseDeclaratorInternal(D, DirectDeclParser);
2211193326Sed
2212193326Sed    if (D.getNumTypeObjects() > 0) {
2213193326Sed      // C++ [dcl.ref]p4: There shall be no references to references.
2214193326Sed      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
2215193326Sed      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
2216193326Sed        if (const IdentifierInfo *II = D.getIdentifier())
2217193326Sed          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2218193326Sed           << II;
2219193326Sed        else
2220193326Sed          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
2221193326Sed            << "type name";
2222193326Sed
2223193326Sed        // Once we've complained about the reference-to-reference, we
2224193326Sed        // can go ahead and build the (technically ill-formed)
2225193326Sed        // declarator: reference collapsing will take care of it.
2226193326Sed      }
2227193326Sed    }
2228193326Sed
2229193326Sed    // Remember that we parsed a reference type. It doesn't have type-quals.
2230193326Sed    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
2231193326Sed                                                DS.TakeAttributes(),
2232193326Sed                                                Kind == tok::amp),
2233193326Sed                  SourceLocation());
2234193326Sed  }
2235193326Sed}
2236193326Sed
2237193326Sed/// ParseDirectDeclarator
2238193326Sed///       direct-declarator: [C99 6.7.5]
2239193326Sed/// [C99]   identifier
2240193326Sed///         '(' declarator ')'
2241193326Sed/// [GNU]   '(' attributes declarator ')'
2242193326Sed/// [C90]   direct-declarator '[' constant-expression[opt] ']'
2243193326Sed/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2244193326Sed/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2245193326Sed/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2246193326Sed/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
2247193326Sed///         direct-declarator '(' parameter-type-list ')'
2248193326Sed///         direct-declarator '(' identifier-list[opt] ')'
2249193326Sed/// [GNU]   direct-declarator '(' parameter-forward-declarations
2250193326Sed///                    parameter-type-list[opt] ')'
2251193326Sed/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
2252193326Sed///                    cv-qualifier-seq[opt] exception-specification[opt]
2253193326Sed/// [C++]   declarator-id
2254193326Sed///
2255193326Sed///       declarator-id: [C++ 8]
2256193326Sed///         id-expression
2257193326Sed///         '::'[opt] nested-name-specifier[opt] type-name
2258193326Sed///
2259193326Sed///       id-expression: [C++ 5.1]
2260193326Sed///         unqualified-id
2261198092Srdivacky///         qualified-id
2262193326Sed///
2263193326Sed///       unqualified-id: [C++ 5.1]
2264198092Srdivacky///         identifier
2265193326Sed///         operator-function-id
2266198092Srdivacky///         conversion-function-id
2267198092Srdivacky///          '~' class-name
2268193326Sed///         template-id
2269193326Sed///
2270193326Sedvoid Parser::ParseDirectDeclarator(Declarator &D) {
2271193326Sed  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
2272193326Sed
2273193326Sed  if (getLang().CPlusPlus) {
2274193326Sed    if (D.mayHaveIdentifier()) {
2275193326Sed      // ParseDeclaratorInternal might already have parsed the scope.
2276193326Sed      bool afterCXXScope = D.getCXXScopeSpec().isSet() ||
2277198092Srdivacky        ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), /*ObjectType=*/0,
2278198092Srdivacky                                       true);
2279193326Sed      if (afterCXXScope) {
2280193326Sed        // Change the declaration context for name lookup, until this function
2281193326Sed        // is exited (and the declarator has been parsed).
2282193326Sed        DeclScopeObj.EnterDeclaratorScope();
2283193326Sed      }
2284193326Sed
2285193326Sed      if (Tok.is(tok::identifier)) {
2286193326Sed        assert(Tok.getIdentifierInfo() && "Not an identifier?");
2287193326Sed
2288193326Sed        // If this identifier is the name of the current class, it's a
2289198092Srdivacky        // constructor name.
2290193326Sed        if (!D.getDeclSpec().hasTypeSpecifier() &&
2291193326Sed            Actions.isCurrentClassName(*Tok.getIdentifierInfo(),CurScope)) {
2292198092Srdivacky          CXXScopeSpec *SS = afterCXXScope? &D.getCXXScopeSpec() : 0;
2293193326Sed          D.setConstructor(Actions.getTypeName(*Tok.getIdentifierInfo(),
2294198092Srdivacky                                               Tok.getLocation(), CurScope, SS),
2295193326Sed                           Tok.getLocation());
2296193326Sed        // This is a normal identifier.
2297193326Sed        } else
2298193326Sed          D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2299193326Sed        ConsumeToken();
2300193326Sed        goto PastIdentifier;
2301193326Sed      } else if (Tok.is(tok::annot_template_id)) {
2302198092Srdivacky        TemplateIdAnnotation *TemplateId
2303193326Sed          = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
2304193326Sed
2305198092Srdivacky        D.setTemplateId(TemplateId);
2306193326Sed        ConsumeToken();
2307193326Sed        goto PastIdentifier;
2308193326Sed      } else if (Tok.is(tok::kw_operator)) {
2309193326Sed        SourceLocation OperatorLoc = Tok.getLocation();
2310193326Sed        SourceLocation EndLoc;
2311193326Sed
2312193326Sed        // First try the name of an overloaded operator
2313193326Sed        if (OverloadedOperatorKind Op = TryParseOperatorFunctionId(&EndLoc)) {
2314193326Sed          D.setOverloadedOperator(Op, OperatorLoc, EndLoc);
2315193326Sed        } else {
2316193326Sed          // This must be a conversion function (C++ [class.conv.fct]).
2317193326Sed          if (TypeTy *ConvType = ParseConversionFunctionId(&EndLoc))
2318193326Sed            D.setConversionFunction(ConvType, OperatorLoc, EndLoc);
2319193326Sed          else {
2320193326Sed            D.SetIdentifier(0, Tok.getLocation());
2321193326Sed          }
2322193326Sed        }
2323193326Sed        goto PastIdentifier;
2324193326Sed      } else if (Tok.is(tok::tilde)) {
2325193326Sed        // This should be a C++ destructor.
2326193326Sed        SourceLocation TildeLoc = ConsumeToken();
2327198092Srdivacky        if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
2328193326Sed          // FIXME: Inaccurate.
2329193326Sed          SourceLocation NameLoc = Tok.getLocation();
2330193326Sed          SourceLocation EndLoc;
2331198092Srdivacky          CXXScopeSpec *SS = afterCXXScope? &D.getCXXScopeSpec() : 0;
2332198092Srdivacky          TypeResult Type = ParseClassName(EndLoc, SS, true);
2333193326Sed          if (Type.isInvalid())
2334193326Sed            D.SetIdentifier(0, TildeLoc);
2335193326Sed          else
2336193326Sed            D.setDestructor(Type.get(), TildeLoc, NameLoc);
2337193326Sed        } else {
2338198092Srdivacky          Diag(Tok, diag::err_destructor_class_name);
2339193326Sed          D.SetIdentifier(0, TildeLoc);
2340193326Sed        }
2341193326Sed        goto PastIdentifier;
2342193326Sed      }
2343193326Sed
2344193326Sed      // If we reached this point, token is not identifier and not '~'.
2345193326Sed
2346193326Sed      if (afterCXXScope) {
2347193326Sed        Diag(Tok, diag::err_expected_unqualified_id);
2348193326Sed        D.SetIdentifier(0, Tok.getLocation());
2349193326Sed        D.setInvalidType(true);
2350193326Sed        goto PastIdentifier;
2351193326Sed      }
2352193326Sed    }
2353193326Sed  }
2354193326Sed
2355193326Sed  // If we reached this point, we are either in C/ObjC or the token didn't
2356193326Sed  // satisfy any of the C++-specific checks.
2357193326Sed  if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
2358193326Sed    assert(!getLang().CPlusPlus &&
2359193326Sed           "There's a C++-specific check for tok::identifier above");
2360193326Sed    assert(Tok.getIdentifierInfo() && "Not an identifier?");
2361193326Sed    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
2362193326Sed    ConsumeToken();
2363193326Sed  } else if (Tok.is(tok::l_paren)) {
2364193326Sed    // direct-declarator: '(' declarator ')'
2365193326Sed    // direct-declarator: '(' attributes declarator ')'
2366193326Sed    // Example: 'char (*X)'   or 'int (*XX)(void)'
2367193326Sed    ParseParenDeclarator(D);
2368193326Sed  } else if (D.mayOmitIdentifier()) {
2369193326Sed    // This could be something simple like "int" (in which case the declarator
2370193326Sed    // portion is empty), if an abstract-declarator is allowed.
2371193326Sed    D.SetIdentifier(0, Tok.getLocation());
2372193326Sed  } else {
2373193326Sed    if (D.getContext() == Declarator::MemberContext)
2374193326Sed      Diag(Tok, diag::err_expected_member_name_or_semi)
2375193326Sed        << D.getDeclSpec().getSourceRange();
2376193326Sed    else if (getLang().CPlusPlus)
2377193326Sed      Diag(Tok, diag::err_expected_unqualified_id);
2378193326Sed    else
2379193326Sed      Diag(Tok, diag::err_expected_ident_lparen);
2380193326Sed    D.SetIdentifier(0, Tok.getLocation());
2381193326Sed    D.setInvalidType(true);
2382193326Sed  }
2383198092Srdivacky
2384193326Sed PastIdentifier:
2385193326Sed  assert(D.isPastIdentifier() &&
2386193326Sed         "Haven't past the location of the identifier yet?");
2387198092Srdivacky
2388193326Sed  while (1) {
2389193326Sed    if (Tok.is(tok::l_paren)) {
2390193326Sed      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
2391193326Sed      // In such a case, check if we actually have a function declarator; if it
2392193326Sed      // is not, the declarator has been fully parsed.
2393193326Sed      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
2394193326Sed        // When not in file scope, warn for ambiguous function declarators, just
2395193326Sed        // in case the author intended it as a variable definition.
2396193326Sed        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
2397193326Sed        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
2398193326Sed          break;
2399193326Sed      }
2400193326Sed      ParseFunctionDeclarator(ConsumeParen(), D);
2401193326Sed    } else if (Tok.is(tok::l_square)) {
2402193326Sed      ParseBracketDeclarator(D);
2403193326Sed    } else {
2404193326Sed      break;
2405193326Sed    }
2406193326Sed  }
2407193326Sed}
2408193326Sed
2409193326Sed/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
2410193326Sed/// only called before the identifier, so these are most likely just grouping
2411198092Srdivacky/// parens for precedence.  If we find that these are actually function
2412193326Sed/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
2413193326Sed///
2414193326Sed///       direct-declarator:
2415193326Sed///         '(' declarator ')'
2416193326Sed/// [GNU]   '(' attributes declarator ')'
2417193326Sed///         direct-declarator '(' parameter-type-list ')'
2418193326Sed///         direct-declarator '(' identifier-list[opt] ')'
2419193326Sed/// [GNU]   direct-declarator '(' parameter-forward-declarations
2420193326Sed///                    parameter-type-list[opt] ')'
2421193326Sed///
2422193326Sedvoid Parser::ParseParenDeclarator(Declarator &D) {
2423193326Sed  SourceLocation StartLoc = ConsumeParen();
2424193326Sed  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
2425198092Srdivacky
2426193326Sed  // Eat any attributes before we look at whether this is a grouping or function
2427193326Sed  // declarator paren.  If this is a grouping paren, the attribute applies to
2428193326Sed  // the type being built up, for example:
2429193326Sed  //     int (__attribute__(()) *x)(long y)
2430193326Sed  // If this ends up not being a grouping paren, the attribute applies to the
2431193326Sed  // first argument, for example:
2432193326Sed  //     int (__attribute__(()) int x)
2433193326Sed  // In either case, we need to eat any attributes to be able to determine what
2434193326Sed  // sort of paren this is.
2435193326Sed  //
2436193326Sed  AttributeList *AttrList = 0;
2437193326Sed  bool RequiresArg = false;
2438193326Sed  if (Tok.is(tok::kw___attribute)) {
2439193326Sed    AttrList = ParseAttributes();
2440198092Srdivacky
2441193326Sed    // We require that the argument list (if this is a non-grouping paren) be
2442193326Sed    // present even if the attribute list was empty.
2443193326Sed    RequiresArg = true;
2444193326Sed  }
2445193326Sed  // Eat any Microsoft extensions.
2446194179Sed  if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
2447194179Sed       Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___w64) ||
2448194179Sed       Tok.is(tok::kw___ptr64)) {
2449194179Sed    AttrList = ParseMicrosoftTypeAttributes(AttrList);
2450194179Sed  }
2451198092Srdivacky
2452193326Sed  // If we haven't past the identifier yet (or where the identifier would be
2453193326Sed  // stored, if this is an abstract declarator), then this is probably just
2454193326Sed  // grouping parens. However, if this could be an abstract-declarator, then
2455193326Sed  // this could also be the start of function arguments (consider 'void()').
2456193326Sed  bool isGrouping;
2457198092Srdivacky
2458193326Sed  if (!D.mayOmitIdentifier()) {
2459193326Sed    // If this can't be an abstract-declarator, this *must* be a grouping
2460193326Sed    // paren, because we haven't seen the identifier yet.
2461193326Sed    isGrouping = true;
2462193326Sed  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
2463193326Sed             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
2464193326Sed             isDeclarationSpecifier()) {       // 'int(int)' is a function.
2465193326Sed    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
2466193326Sed    // considered to be a type, not a K&R identifier-list.
2467193326Sed    isGrouping = false;
2468193326Sed  } else {
2469193326Sed    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
2470193326Sed    isGrouping = true;
2471193326Sed  }
2472198092Srdivacky
2473193326Sed  // If this is a grouping paren, handle:
2474193326Sed  // direct-declarator: '(' declarator ')'
2475193326Sed  // direct-declarator: '(' attributes declarator ')'
2476193326Sed  if (isGrouping) {
2477193326Sed    bool hadGroupingParens = D.hasGroupingParens();
2478193326Sed    D.setGroupingParens(true);
2479193326Sed    if (AttrList)
2480193326Sed      D.AddAttributes(AttrList, SourceLocation());
2481193326Sed
2482193326Sed    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
2483193326Sed    // Match the ')'.
2484193326Sed    SourceLocation Loc = MatchRHSPunctuation(tok::r_paren, StartLoc);
2485193326Sed
2486193326Sed    D.setGroupingParens(hadGroupingParens);
2487193326Sed    D.SetRangeEnd(Loc);
2488193326Sed    return;
2489193326Sed  }
2490198092Srdivacky
2491193326Sed  // Okay, if this wasn't a grouping paren, it must be the start of a function
2492193326Sed  // argument list.  Recognize that this declarator will never have an
2493193326Sed  // identifier (and remember where it would have been), then call into
2494193326Sed  // ParseFunctionDeclarator to handle of argument list.
2495193326Sed  D.SetIdentifier(0, Tok.getLocation());
2496193326Sed
2497193326Sed  ParseFunctionDeclarator(StartLoc, D, AttrList, RequiresArg);
2498193326Sed}
2499193326Sed
2500193326Sed/// ParseFunctionDeclarator - We are after the identifier and have parsed the
2501193326Sed/// declarator D up to a paren, which indicates that we are parsing function
2502193326Sed/// arguments.
2503193326Sed///
2504193326Sed/// If AttrList is non-null, then the caller parsed those arguments immediately
2505193326Sed/// after the open paren - they should be considered to be the first argument of
2506193326Sed/// a parameter.  If RequiresArg is true, then the first argument of the
2507193326Sed/// function is required to be present and required to not be an identifier
2508193326Sed/// list.
2509193326Sed///
2510193326Sed/// This method also handles this portion of the grammar:
2511193326Sed///       parameter-type-list: [C99 6.7.5]
2512193326Sed///         parameter-list
2513193326Sed///         parameter-list ',' '...'
2514198092Srdivacky/// [C++]   parameter-list '...'
2515193326Sed///
2516193326Sed///       parameter-list: [C99 6.7.5]
2517193326Sed///         parameter-declaration
2518193326Sed///         parameter-list ',' parameter-declaration
2519193326Sed///
2520193326Sed///       parameter-declaration: [C99 6.7.5]
2521193326Sed///         declaration-specifiers declarator
2522193326Sed/// [C++]   declaration-specifiers declarator '=' assignment-expression
2523193326Sed/// [GNU]   declaration-specifiers declarator attributes
2524193326Sed///         declaration-specifiers abstract-declarator[opt]
2525193326Sed/// [C++]   declaration-specifiers abstract-declarator[opt]
2526193326Sed///           '=' assignment-expression
2527193326Sed/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
2528193326Sed///
2529193326Sed/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]"
2530193326Sed/// and "exception-specification[opt]".
2531193326Sed///
2532193326Sedvoid Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
2533193326Sed                                     AttributeList *AttrList,
2534193326Sed                                     bool RequiresArg) {
2535193326Sed  // lparen is already consumed!
2536193326Sed  assert(D.isPastIdentifier() && "Should not call before identifier!");
2537198092Srdivacky
2538193326Sed  // This parameter list may be empty.
2539193326Sed  if (Tok.is(tok::r_paren)) {
2540193326Sed    if (RequiresArg) {
2541193326Sed      Diag(Tok, diag::err_argument_required_after_attribute);
2542193326Sed      delete AttrList;
2543193326Sed    }
2544193326Sed
2545198092Srdivacky    SourceLocation RParenLoc = ConsumeParen();  // Eat the closing ')'.
2546198092Srdivacky    SourceLocation EndLoc = RParenLoc;
2547193326Sed
2548193326Sed    // cv-qualifier-seq[opt].
2549193326Sed    DeclSpec DS;
2550193326Sed    bool hasExceptionSpec = false;
2551193326Sed    SourceLocation ThrowLoc;
2552193326Sed    bool hasAnyExceptionSpec = false;
2553193326Sed    llvm::SmallVector<TypeTy*, 2> Exceptions;
2554193326Sed    llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2555193326Sed    if (getLang().CPlusPlus) {
2556193326Sed      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2557193326Sed      if (!DS.getSourceRange().getEnd().isInvalid())
2558198092Srdivacky        EndLoc = DS.getSourceRange().getEnd();
2559193326Sed
2560193326Sed      // Parse exception-specification[opt].
2561193326Sed      if (Tok.is(tok::kw_throw)) {
2562193326Sed        hasExceptionSpec = true;
2563193326Sed        ThrowLoc = Tok.getLocation();
2564198092Srdivacky        ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
2565193326Sed                                    hasAnyExceptionSpec);
2566193326Sed        assert(Exceptions.size() == ExceptionRanges.size() &&
2567193326Sed               "Produced different number of exception types and ranges.");
2568193326Sed      }
2569193326Sed    }
2570193326Sed
2571193326Sed    // Remember that we parsed a function type, and remember the attributes.
2572193326Sed    // int() -> no prototype, no '...'.
2573193326Sed    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
2574193326Sed                                               /*variadic*/ false,
2575193326Sed                                               SourceLocation(),
2576193326Sed                                               /*arglist*/ 0, 0,
2577193326Sed                                               DS.getTypeQualifiers(),
2578193326Sed                                               hasExceptionSpec, ThrowLoc,
2579193326Sed                                               hasAnyExceptionSpec,
2580193326Sed                                               Exceptions.data(),
2581193326Sed                                               ExceptionRanges.data(),
2582193326Sed                                               Exceptions.size(),
2583198092Srdivacky                                               LParenLoc, RParenLoc, D),
2584198092Srdivacky                  EndLoc);
2585193326Sed    return;
2586193326Sed  }
2587193326Sed
2588193326Sed  // Alternatively, this parameter list may be an identifier list form for a
2589193326Sed  // K&R-style function:  void foo(a,b,c)
2590193326Sed  if (!getLang().CPlusPlus && Tok.is(tok::identifier)) {
2591193326Sed    if (!TryAnnotateTypeOrScopeToken()) {
2592193326Sed      // K&R identifier lists can't have typedefs as identifiers, per
2593193326Sed      // C99 6.7.5.3p11.
2594193326Sed      if (RequiresArg) {
2595193326Sed        Diag(Tok, diag::err_argument_required_after_attribute);
2596193326Sed        delete AttrList;
2597193326Sed      }
2598193326Sed      // Identifier list.  Note that '(' identifier-list ')' is only allowed for
2599193326Sed      // normal declarators, not for abstract-declarators.
2600193326Sed      return ParseFunctionDeclaratorIdentifierList(LParenLoc, D);
2601193326Sed    }
2602193326Sed  }
2603198092Srdivacky
2604193326Sed  // Finally, a normal, non-empty parameter type list.
2605198092Srdivacky
2606193326Sed  // Build up an array of information about the parsed arguments.
2607193326Sed  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2608193326Sed
2609193326Sed  // Enter function-declaration scope, limiting any declarators to the
2610193326Sed  // function prototype scope, including parameter declarators.
2611193326Sed  ParseScope PrototypeScope(this,
2612193326Sed                            Scope::FunctionPrototypeScope|Scope::DeclScope);
2613198092Srdivacky
2614193326Sed  bool IsVariadic = false;
2615193326Sed  SourceLocation EllipsisLoc;
2616193326Sed  while (1) {
2617193326Sed    if (Tok.is(tok::ellipsis)) {
2618193326Sed      IsVariadic = true;
2619193326Sed      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
2620193326Sed      break;
2621193326Sed    }
2622198092Srdivacky
2623193326Sed    SourceLocation DSStart = Tok.getLocation();
2624198092Srdivacky
2625193326Sed    // Parse the declaration-specifiers.
2626193326Sed    DeclSpec DS;
2627193326Sed
2628193326Sed    // If the caller parsed attributes for the first argument, add them now.
2629193326Sed    if (AttrList) {
2630193326Sed      DS.AddAttributes(AttrList);
2631193326Sed      AttrList = 0;  // Only apply the attributes to the first parameter.
2632193326Sed    }
2633193326Sed    ParseDeclarationSpecifiers(DS);
2634198092Srdivacky
2635193326Sed    // Parse the declarator.  This is "PrototypeContext", because we must
2636193326Sed    // accept either 'declarator' or 'abstract-declarator' here.
2637193326Sed    Declarator ParmDecl(DS, Declarator::PrototypeContext);
2638193326Sed    ParseDeclarator(ParmDecl);
2639193326Sed
2640193326Sed    // Parse GNU attributes, if present.
2641193326Sed    if (Tok.is(tok::kw___attribute)) {
2642193326Sed      SourceLocation Loc;
2643193326Sed      AttributeList *AttrList = ParseAttributes(&Loc);
2644193326Sed      ParmDecl.AddAttributes(AttrList, Loc);
2645193326Sed    }
2646198092Srdivacky
2647193326Sed    // Remember this parsed parameter in ParamInfo.
2648193326Sed    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
2649198092Srdivacky
2650193326Sed    // DefArgToks is used when the parsing of default arguments needs
2651193326Sed    // to be delayed.
2652193326Sed    CachedTokens *DefArgToks = 0;
2653193326Sed
2654193326Sed    // If no parameter was specified, verify that *something* was specified,
2655193326Sed    // otherwise we have a missing type and identifier.
2656193326Sed    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
2657193326Sed        ParmDecl.getNumTypeObjects() == 0) {
2658193326Sed      // Completely missing, emit error.
2659193326Sed      Diag(DSStart, diag::err_missing_param);
2660193326Sed    } else {
2661193326Sed      // Otherwise, we have something.  Add it and let semantic analysis try
2662193326Sed      // to grok it and add the result to the ParamInfo we are building.
2663198092Srdivacky
2664193326Sed      // Inform the actions module about the parameter declarator, so it gets
2665193326Sed      // added to the current scope.
2666193326Sed      DeclPtrTy Param = Actions.ActOnParamDeclarator(CurScope, ParmDecl);
2667193326Sed
2668193326Sed      // Parse the default argument, if any. We parse the default
2669193326Sed      // arguments in all dialects; the semantic analysis in
2670193326Sed      // ActOnParamDefaultArgument will reject the default argument in
2671193326Sed      // C.
2672193326Sed      if (Tok.is(tok::equal)) {
2673193326Sed        SourceLocation EqualLoc = Tok.getLocation();
2674193326Sed
2675193326Sed        // Parse the default argument
2676193326Sed        if (D.getContext() == Declarator::MemberContext) {
2677193326Sed          // If we're inside a class definition, cache the tokens
2678193326Sed          // corresponding to the default argument. We'll actually parse
2679193326Sed          // them when we see the end of the class definition.
2680193326Sed          // FIXME: Templates will require something similar.
2681193326Sed          // FIXME: Can we use a smart pointer for Toks?
2682193326Sed          DefArgToks = new CachedTokens;
2683193326Sed
2684198092Srdivacky          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
2685193326Sed                                    tok::semi, false)) {
2686193326Sed            delete DefArgToks;
2687193326Sed            DefArgToks = 0;
2688193326Sed            Actions.ActOnParamDefaultArgumentError(Param);
2689193326Sed          } else
2690198092Srdivacky            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
2691194179Sed                                                (*DefArgToks)[1].getLocation());
2692193326Sed        } else {
2693193326Sed          // Consume the '='.
2694193326Sed          ConsumeToken();
2695198092Srdivacky
2696193326Sed          OwningExprResult DefArgResult(ParseAssignmentExpression());
2697193326Sed          if (DefArgResult.isInvalid()) {
2698193326Sed            Actions.ActOnParamDefaultArgumentError(Param);
2699193326Sed            SkipUntil(tok::comma, tok::r_paren, true, true);
2700193326Sed          } else {
2701193326Sed            // Inform the actions module about the default argument
2702193326Sed            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
2703193326Sed                                              move(DefArgResult));
2704193326Sed          }
2705193326Sed        }
2706193326Sed      }
2707198092Srdivacky
2708198092Srdivacky      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2709198092Srdivacky                                          ParmDecl.getIdentifierLoc(), Param,
2710193326Sed                                          DefArgToks));
2711193326Sed    }
2712193326Sed
2713193326Sed    // If the next token is a comma, consume it and keep reading arguments.
2714198092Srdivacky    if (Tok.isNot(tok::comma)) {
2715198092Srdivacky      if (Tok.is(tok::ellipsis)) {
2716198092Srdivacky        IsVariadic = true;
2717198092Srdivacky        EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
2718198092Srdivacky
2719198092Srdivacky        if (!getLang().CPlusPlus) {
2720198092Srdivacky          // We have ellipsis without a preceding ',', which is ill-formed
2721198092Srdivacky          // in C. Complain and provide the fix.
2722198092Srdivacky          Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
2723198092Srdivacky            << CodeModificationHint::CreateInsertion(EllipsisLoc, ", ");
2724198092Srdivacky        }
2725198092Srdivacky      }
2726198092Srdivacky
2727198092Srdivacky      break;
2728198092Srdivacky    }
2729198092Srdivacky
2730193326Sed    // Consume the comma.
2731193326Sed    ConsumeToken();
2732193326Sed  }
2733198092Srdivacky
2734193326Sed  // Leave prototype scope.
2735193326Sed  PrototypeScope.Exit();
2736198092Srdivacky
2737193326Sed  // If we have the closing ')', eat it.
2738198092Srdivacky  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2739198092Srdivacky  SourceLocation EndLoc = RParenLoc;
2740193326Sed
2741193326Sed  DeclSpec DS;
2742193326Sed  bool hasExceptionSpec = false;
2743193326Sed  SourceLocation ThrowLoc;
2744193326Sed  bool hasAnyExceptionSpec = false;
2745193326Sed  llvm::SmallVector<TypeTy*, 2> Exceptions;
2746193326Sed  llvm::SmallVector<SourceRange, 2> ExceptionRanges;
2747193326Sed  if (getLang().CPlusPlus) {
2748193326Sed    // Parse cv-qualifier-seq[opt].
2749193326Sed    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2750193326Sed      if (!DS.getSourceRange().getEnd().isInvalid())
2751198092Srdivacky        EndLoc = DS.getSourceRange().getEnd();
2752193326Sed
2753193326Sed    // Parse exception-specification[opt].
2754193326Sed    if (Tok.is(tok::kw_throw)) {
2755193326Sed      hasExceptionSpec = true;
2756193326Sed      ThrowLoc = Tok.getLocation();
2757198092Srdivacky      ParseExceptionSpecification(EndLoc, Exceptions, ExceptionRanges,
2758193326Sed                                  hasAnyExceptionSpec);
2759193326Sed      assert(Exceptions.size() == ExceptionRanges.size() &&
2760193326Sed             "Produced different number of exception types and ranges.");
2761193326Sed    }
2762193326Sed  }
2763193326Sed
2764193326Sed  // Remember that we parsed a function type, and remember the attributes.
2765193326Sed  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
2766193326Sed                                             EllipsisLoc,
2767193326Sed                                             ParamInfo.data(), ParamInfo.size(),
2768193326Sed                                             DS.getTypeQualifiers(),
2769193326Sed                                             hasExceptionSpec, ThrowLoc,
2770193326Sed                                             hasAnyExceptionSpec,
2771193326Sed                                             Exceptions.data(),
2772193326Sed                                             ExceptionRanges.data(),
2773198092Srdivacky                                             Exceptions.size(),
2774198092Srdivacky                                             LParenLoc, RParenLoc, D),
2775198092Srdivacky                EndLoc);
2776193326Sed}
2777193326Sed
2778193326Sed/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
2779193326Sed/// we found a K&R-style identifier list instead of a type argument list.  The
2780193326Sed/// current token is known to be the first identifier in the list.
2781193326Sed///
2782193326Sed///       identifier-list: [C99 6.7.5]
2783193326Sed///         identifier
2784193326Sed///         identifier-list ',' identifier
2785193326Sed///
2786193326Sedvoid Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
2787193326Sed                                                   Declarator &D) {
2788193326Sed  // Build up an array of information about the parsed arguments.
2789193326Sed  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
2790193326Sed  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
2791198092Srdivacky
2792193326Sed  // If there was no identifier specified for the declarator, either we are in
2793193326Sed  // an abstract-declarator, or we are in a parameter declarator which was found
2794193326Sed  // to be abstract.  In abstract-declarators, identifier lists are not valid:
2795193326Sed  // diagnose this.
2796193326Sed  if (!D.getIdentifier())
2797193326Sed    Diag(Tok, diag::ext_ident_list_in_param);
2798193326Sed
2799193326Sed  // Tok is known to be the first identifier in the list.  Remember this
2800193326Sed  // identifier in ParamInfo.
2801193326Sed  ParamsSoFar.insert(Tok.getIdentifierInfo());
2802193326Sed  ParamInfo.push_back(DeclaratorChunk::ParamInfo(Tok.getIdentifierInfo(),
2803193326Sed                                                 Tok.getLocation(),
2804193326Sed                                                 DeclPtrTy()));
2805198092Srdivacky
2806193326Sed  ConsumeToken();  // eat the first identifier.
2807198092Srdivacky
2808193326Sed  while (Tok.is(tok::comma)) {
2809193326Sed    // Eat the comma.
2810193326Sed    ConsumeToken();
2811198092Srdivacky
2812193326Sed    // If this isn't an identifier, report the error and skip until ')'.
2813193326Sed    if (Tok.isNot(tok::identifier)) {
2814193326Sed      Diag(Tok, diag::err_expected_ident);
2815193326Sed      SkipUntil(tok::r_paren);
2816193326Sed      return;
2817193326Sed    }
2818193326Sed
2819193326Sed    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
2820193326Sed
2821193326Sed    // Reject 'typedef int y; int test(x, y)', but continue parsing.
2822193326Sed    if (Actions.getTypeName(*ParmII, Tok.getLocation(), CurScope))
2823193326Sed      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
2824198092Srdivacky
2825193326Sed    // Verify that the argument identifier has not already been mentioned.
2826193326Sed    if (!ParamsSoFar.insert(ParmII)) {
2827193326Sed      Diag(Tok, diag::err_param_redefinition) << ParmII;
2828193326Sed    } else {
2829193326Sed      // Remember this identifier in ParamInfo.
2830193326Sed      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
2831193326Sed                                                     Tok.getLocation(),
2832193326Sed                                                     DeclPtrTy()));
2833193326Sed    }
2834198092Srdivacky
2835193326Sed    // Eat the identifier.
2836193326Sed    ConsumeToken();
2837193326Sed  }
2838193326Sed
2839193326Sed  // If we have the closing ')', eat it and we're done.
2840193326Sed  SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2841193326Sed
2842193326Sed  // Remember that we parsed a function type, and remember the attributes.  This
2843193326Sed  // function type is always a K&R style function type, which is not varargs and
2844193326Sed  // has no prototype.
2845193326Sed  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
2846193326Sed                                             SourceLocation(),
2847193326Sed                                             &ParamInfo[0], ParamInfo.size(),
2848193326Sed                                             /*TypeQuals*/0,
2849193326Sed                                             /*exception*/false,
2850193326Sed                                             SourceLocation(), false, 0, 0, 0,
2851198092Srdivacky                                             LParenLoc, RLoc, D),
2852193326Sed                RLoc);
2853193326Sed}
2854193326Sed
2855193326Sed/// [C90]   direct-declarator '[' constant-expression[opt] ']'
2856193326Sed/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
2857193326Sed/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
2858193326Sed/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
2859193326Sed/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
2860193326Sedvoid Parser::ParseBracketDeclarator(Declarator &D) {
2861193326Sed  SourceLocation StartLoc = ConsumeBracket();
2862198092Srdivacky
2863193326Sed  // C array syntax has many features, but by-far the most common is [] and [4].
2864193326Sed  // This code does a fast path to handle some of the most obvious cases.
2865193326Sed  if (Tok.getKind() == tok::r_square) {
2866193326Sed    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2867193326Sed    // Remember that we parsed the empty array type.
2868193326Sed    OwningExprResult NumElements(Actions);
2869198092Srdivacky    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
2870198092Srdivacky                                            StartLoc, EndLoc),
2871193326Sed                  EndLoc);
2872193326Sed    return;
2873193326Sed  } else if (Tok.getKind() == tok::numeric_constant &&
2874193326Sed             GetLookAheadToken(1).is(tok::r_square)) {
2875193326Sed    // [4] is very common.  Parse the numeric constant expression.
2876193326Sed    OwningExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
2877193326Sed    ConsumeToken();
2878193326Sed
2879193326Sed    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2880193326Sed
2881193326Sed    // If there was an error parsing the assignment-expression, recover.
2882193326Sed    if (ExprRes.isInvalid())
2883193326Sed      ExprRes.release();  // Deallocate expr, just use [].
2884198092Srdivacky
2885193326Sed    // Remember that we parsed a array type, and remember its features.
2886198092Srdivacky    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0, ExprRes.release(),
2887198092Srdivacky                                            StartLoc, EndLoc),
2888193326Sed                  EndLoc);
2889193326Sed    return;
2890193326Sed  }
2891198092Srdivacky
2892193326Sed  // If valid, this location is the position where we read the 'static' keyword.
2893193326Sed  SourceLocation StaticLoc;
2894193326Sed  if (Tok.is(tok::kw_static))
2895193326Sed    StaticLoc = ConsumeToken();
2896198092Srdivacky
2897193326Sed  // If there is a type-qualifier-list, read it now.
2898193326Sed  // Type qualifiers in an array subscript are a C99 feature.
2899193326Sed  DeclSpec DS;
2900193326Sed  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
2901198092Srdivacky
2902193326Sed  // If we haven't already read 'static', check to see if there is one after the
2903193326Sed  // type-qualifier-list.
2904193326Sed  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
2905193326Sed    StaticLoc = ConsumeToken();
2906198092Srdivacky
2907193326Sed  // Handle "direct-declarator [ type-qual-list[opt] * ]".
2908193326Sed  bool isStar = false;
2909193326Sed  OwningExprResult NumElements(Actions);
2910198092Srdivacky
2911193326Sed  // Handle the case where we have '[*]' as the array size.  However, a leading
2912193326Sed  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
2913193326Sed  // the the token after the star is a ']'.  Since stars in arrays are
2914193326Sed  // infrequent, use of lookahead is not costly here.
2915193326Sed  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
2916193326Sed    ConsumeToken();  // Eat the '*'.
2917193326Sed
2918193326Sed    if (StaticLoc.isValid()) {
2919193326Sed      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
2920193326Sed      StaticLoc = SourceLocation();  // Drop the static.
2921193326Sed    }
2922193326Sed    isStar = true;
2923193326Sed  } else if (Tok.isNot(tok::r_square)) {
2924193326Sed    // Note, in C89, this production uses the constant-expr production instead
2925193326Sed    // of assignment-expr.  The only difference is that assignment-expr allows
2926193326Sed    // things like '=' and '*='.  Sema rejects these in C89 mode because they
2927193326Sed    // are not i-c-e's, so we don't need to distinguish between the two here.
2928198092Srdivacky
2929194613Sed    // Parse the constant-expression or assignment-expression now (depending
2930194613Sed    // on dialect).
2931194613Sed    if (getLang().CPlusPlus)
2932194613Sed      NumElements = ParseConstantExpression();
2933194613Sed    else
2934194613Sed      NumElements = ParseAssignmentExpression();
2935193326Sed  }
2936198092Srdivacky
2937193326Sed  // If there was an error parsing the assignment-expression, recover.
2938193326Sed  if (NumElements.isInvalid()) {
2939193326Sed    D.setInvalidType(true);
2940193326Sed    // If the expression was invalid, skip it.
2941193326Sed    SkipUntil(tok::r_square);
2942193326Sed    return;
2943193326Sed  }
2944193326Sed
2945193326Sed  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
2946193326Sed
2947193326Sed  // Remember that we parsed a array type, and remember its features.
2948193326Sed  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
2949193326Sed                                          StaticLoc.isValid(), isStar,
2950198092Srdivacky                                          NumElements.release(),
2951198092Srdivacky                                          StartLoc, EndLoc),
2952193326Sed                EndLoc);
2953193326Sed}
2954193326Sed
2955193326Sed/// [GNU]   typeof-specifier:
2956193326Sed///           typeof ( expressions )
2957193326Sed///           typeof ( type-name )
2958193326Sed/// [GNU/C++] typeof unary-expression
2959193326Sed///
2960193326Sedvoid Parser::ParseTypeofSpecifier(DeclSpec &DS) {
2961193326Sed  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
2962193326Sed  Token OpTok = Tok;
2963193326Sed  SourceLocation StartLoc = ConsumeToken();
2964193326Sed
2965193326Sed  bool isCastExpr;
2966193326Sed  TypeTy *CastTy;
2967193326Sed  SourceRange CastRange;
2968193326Sed  OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok,
2969193326Sed                                                               isCastExpr,
2970193326Sed                                                               CastTy,
2971193326Sed                                                               CastRange);
2972193326Sed
2973193326Sed  if (CastRange.getEnd().isInvalid())
2974193326Sed    // FIXME: Not accurate, the range gets one token more than it should.
2975193326Sed    DS.SetRangeEnd(Tok.getLocation());
2976193326Sed  else
2977193326Sed    DS.SetRangeEnd(CastRange.getEnd());
2978198092Srdivacky
2979193326Sed  if (isCastExpr) {
2980193326Sed    if (!CastTy) {
2981193326Sed      DS.SetTypeSpecError();
2982193326Sed      return;
2983193326Sed    }
2984193326Sed
2985193326Sed    const char *PrevSpec = 0;
2986198092Srdivacky    unsigned DiagID;
2987193326Sed    // Check for duplicate type specifiers (e.g. "int typeof(int)").
2988193326Sed    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
2989198092Srdivacky                           DiagID, CastTy))
2990198092Srdivacky      Diag(StartLoc, DiagID) << PrevSpec;
2991193326Sed    return;
2992193326Sed  }
2993193326Sed
2994193326Sed  // If we get here, the operand to the typeof was an expresion.
2995193326Sed  if (Operand.isInvalid()) {
2996193326Sed    DS.SetTypeSpecError();
2997193326Sed    return;
2998193326Sed  }
2999193326Sed
3000193326Sed  const char *PrevSpec = 0;
3001198092Srdivacky  unsigned DiagID;
3002193326Sed  // Check for duplicate type specifiers (e.g. "int typeof(int)").
3003193326Sed  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
3004198092Srdivacky                         DiagID, Operand.release()))
3005198092Srdivacky    Diag(StartLoc, DiagID) << PrevSpec;
3006193326Sed}
3007