blob: 0b06006d9d0a1c457f9e0766ea75ce74c2b1841b [file] [log] [blame]
Chris Lattnerf7b2e552007-08-25 06:57:03 +00001//===--- ParseDeclCXX.cpp - C++ Declaration Parsing -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf7b2e552007-08-25 06:57:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the C++ Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregor696be932008-04-14 00:13:42 +000014#include "clang/Parse/Parser.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000015#include "clang/Basic/Diagnostic.h"
16#include "clang/Parse/DeclSpec.h"
Chris Lattnerf7b2e552007-08-25 06:57:03 +000017#include "clang/Parse/Scope.h"
Sebastian Redl6008ac32008-11-25 22:21:31 +000018#include "AstGuard.h"
Chris Lattnerf3375de2008-12-18 01:12:00 +000019#include "ExtensionRAIIObject.h"
Chris Lattnerf7b2e552007-08-25 06:57:03 +000020using namespace clang;
21
22/// ParseNamespace - We know that the current token is a namespace keyword. This
23/// may either be a top level namespace or a block-level namespace alias.
24///
25/// namespace-definition: [C++ 7.3: basic.namespace]
26/// named-namespace-definition
27/// unnamed-namespace-definition
28///
29/// unnamed-namespace-definition:
30/// 'namespace' attributes[opt] '{' namespace-body '}'
31///
32/// named-namespace-definition:
33/// original-namespace-definition
34/// extension-namespace-definition
35///
36/// original-namespace-definition:
37/// 'namespace' identifier attributes[opt] '{' namespace-body '}'
38///
39/// extension-namespace-definition:
40/// 'namespace' original-namespace-name '{' namespace-body '}'
41///
42/// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
43/// 'namespace' identifier '=' qualified-namespace-specifier ';'
44///
45Parser::DeclTy *Parser::ParseNamespace(unsigned Context) {
Chris Lattner34a01ad2007-10-09 17:33:22 +000046 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
Chris Lattnerf7b2e552007-08-25 06:57:03 +000047 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
48
49 SourceLocation IdentLoc;
50 IdentifierInfo *Ident = 0;
51
Chris Lattner34a01ad2007-10-09 17:33:22 +000052 if (Tok.is(tok::identifier)) {
Chris Lattnerf7b2e552007-08-25 06:57:03 +000053 Ident = Tok.getIdentifierInfo();
54 IdentLoc = ConsumeToken(); // eat the identifier.
55 }
56
57 // Read label attributes, if present.
58 DeclTy *AttrList = 0;
Chris Lattner34a01ad2007-10-09 17:33:22 +000059 if (Tok.is(tok::kw___attribute))
Chris Lattnerf7b2e552007-08-25 06:57:03 +000060 // FIXME: save these somewhere.
61 AttrList = ParseAttributes();
62
Chris Lattner34a01ad2007-10-09 17:33:22 +000063 if (Tok.is(tok::equal)) {
Chris Lattnerf7b2e552007-08-25 06:57:03 +000064 // FIXME: Verify no attributes were present.
65 // FIXME: parse this.
Chris Lattner34a01ad2007-10-09 17:33:22 +000066 } else if (Tok.is(tok::l_brace)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000067
Chris Lattnerf7b2e552007-08-25 06:57:03 +000068 SourceLocation LBrace = ConsumeBrace();
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000069
70 // Enter a scope for the namespace.
Douglas Gregor95d40792008-12-10 06:34:36 +000071 ParseScope NamespaceScope(this, Scope::DeclScope);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000072
73 DeclTy *NamespcDecl =
74 Actions.ActOnStartNamespaceDef(CurScope, IdentLoc, Ident, LBrace);
75
76 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof))
Chris Lattner9c135722007-08-25 18:15:16 +000077 ParseExternalDeclaration();
Chris Lattnerf7b2e552007-08-25 06:57:03 +000078
Argiris Kirtzidis5f21e592008-05-01 21:44:34 +000079 // Leave the namespace scope.
Douglas Gregor95d40792008-12-10 06:34:36 +000080 NamespaceScope.Exit();
Argiris Kirtzidis5f21e592008-05-01 21:44:34 +000081
Chris Lattnerf7b2e552007-08-25 06:57:03 +000082 SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000083 Actions.ActOnFinishNamespaceDef(NamespcDecl, RBrace);
84
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000085 return NamespcDecl;
Chris Lattnerf7b2e552007-08-25 06:57:03 +000086
Chris Lattnerf7b2e552007-08-25 06:57:03 +000087 } else {
Chris Lattnerf006a222008-11-18 07:48:38 +000088 Diag(Tok, Ident ? diag::err_expected_lbrace :
89 diag::err_expected_ident_lbrace);
Chris Lattnerf7b2e552007-08-25 06:57:03 +000090 }
91
92 return 0;
93}
Chris Lattner806a5f52008-01-12 07:05:38 +000094
95/// ParseLinkage - We know that the current token is a string_literal
96/// and just before that, that extern was seen.
97///
98/// linkage-specification: [C++ 7.5p2: dcl.link]
99/// 'extern' string-literal '{' declaration-seq[opt] '}'
100/// 'extern' string-literal declaration
101///
102Parser::DeclTy *Parser::ParseLinkage(unsigned Context) {
Douglas Gregor61818c52008-11-21 16:10:08 +0000103 assert(Tok.is(tok::string_literal) && "Not a string literal!");
Chris Lattner806a5f52008-01-12 07:05:38 +0000104 llvm::SmallVector<char, 8> LangBuffer;
105 // LangBuffer is guaranteed to be big enough.
106 LangBuffer.resize(Tok.getLength());
107 const char *LangBufPtr = &LangBuffer[0];
108 unsigned StrSize = PP.getSpelling(Tok, LangBufPtr);
109
110 SourceLocation Loc = ConsumeStringToken();
Chris Lattner806a5f52008-01-12 07:05:38 +0000111
Douglas Gregord8028382009-01-05 19:45:36 +0000112 ParseScope LinkageScope(this, Scope::DeclScope);
113 DeclTy *LinkageSpec
114 = Actions.ActOnStartLinkageSpecification(CurScope,
115 /*FIXME: */SourceLocation(),
116 Loc, LangBufPtr, StrSize,
117 Tok.is(tok::l_brace)? Tok.getLocation()
118 : SourceLocation());
119
120 if (Tok.isNot(tok::l_brace)) {
121 ParseDeclarationOrFunctionDefinition();
122 return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec,
123 SourceLocation());
Douglas Gregorad17e372008-12-16 22:23:02 +0000124 }
125
126 SourceLocation LBrace = ConsumeBrace();
Douglas Gregorad17e372008-12-16 22:23:02 +0000127 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
Douglas Gregord8028382009-01-05 19:45:36 +0000128 ParseExternalDeclaration();
Chris Lattner806a5f52008-01-12 07:05:38 +0000129 }
130
Douglas Gregorad17e372008-12-16 22:23:02 +0000131 SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
Douglas Gregord8028382009-01-05 19:45:36 +0000132 return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec, RBrace);
Chris Lattner806a5f52008-01-12 07:05:38 +0000133}
Douglas Gregorec93f442008-04-13 21:30:24 +0000134
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000135/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
136/// using-directive. Assumes that current token is 'using'.
137Parser::DeclTy *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context)
138{
139 assert(Tok.is(tok::kw_using) && "Not using token");
140
141 // Eat 'using'.
142 SourceLocation UsingLoc = ConsumeToken();
143
144 if (Tok.is(tok::kw_namespace)) {
145 // Next token after 'using' is 'namespace' so it must be using-directive
146 return ParseUsingDirective(Context, UsingLoc);
147 } else {
148 // Otherwise, it must be using-declaration.
149 return ParseUsingDeclaration(Context, UsingLoc); //FIXME: It is just stub.
150 }
151}
152
153/// ParseUsingDirective - Parse C++ using-directive, assumes
154/// that current token is 'namespace' and 'using' was already parsed.
155///
156/// using-directive: [C++ 7.3.p4: namespace.udir]
157/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
158/// namespace-name ;
159/// [GNU] using-directive:
160/// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
161/// namespace-name attributes[opt] ;
162///
163Parser::DeclTy *Parser::ParseUsingDirective(unsigned Context,
164 SourceLocation UsingLoc) {
165 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
166
167 // Eat 'namespace'.
168 SourceLocation NamespcLoc = ConsumeToken();
169
170 CXXScopeSpec SS;
171 // Parse (optional) nested-name-specifier.
172 MaybeParseCXXScopeSpecifier(SS);
173
174 AttributeList *AttrList = 0;
175 IdentifierInfo *NamespcName = 0;
176 SourceLocation IdentLoc = SourceLocation();
177
178 // Parse namespace-name.
179 if (!SS.isInvalid() && Tok.is(tok::identifier)) {
180 // Parse identifier.
181 NamespcName = Tok.getIdentifierInfo();
182 IdentLoc = ConsumeToken();
183 // Parse (optional) attributes (most likely GNU strong-using extension)
184 if (Tok.is(tok::kw___attribute)) {
185 AttrList = ParseAttributes();
186 }
187 // Eat ';'.
188 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
189 AttrList? "attributes list" : "namespace name")) {
190 SkipUntil(tok::semi);
191 return 0;
192 }
193 } else {
194 Diag(Tok, diag::err_expected_namespace_name);
195 // If there was invalid namespace name, skip to end of decl, and eat ';'.
196 SkipUntil(tok::semi);
197 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
198 return 0;
199 }
200
201 return Actions.ActOnUsingDirective(CurScope, UsingLoc, NamespcLoc, SS,
202 IdentLoc ,NamespcName, AttrList);
203}
204
205/// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that
206/// 'using' was already seen.
207///
208/// using-declaration: [C++ 7.3.p3: namespace.udecl]
209/// 'using' 'typename'[opt] ::[opt] nested-name-specifier
210/// unqualified-id [TODO]
211/// 'using' :: unqualified-id [TODO]
212///
213Parser::DeclTy *Parser::ParseUsingDeclaration(unsigned Context,
214 SourceLocation UsingLoc) {
215 assert(false && "Not implemented");
216 // FIXME: Implement parsing.
217 return 0;
218}
219
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000220/// ParseClassName - Parse a C++ class-name, which names a class. Note
221/// that we only check that the result names a type; semantic analysis
222/// will need to verify that the type names a class. The result is
223/// either a type or NULL, dependending on whether a type name was
224/// found.
225///
226/// class-name: [C++ 9.1]
227/// identifier
228/// template-id [TODO]
229///
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000230Parser::TypeTy *Parser::ParseClassName(const CXXScopeSpec *SS) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000231 // Parse the class-name.
232 // FIXME: Alternatively, parse a simple-template-id.
233 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000234 Diag(Tok, diag::err_expected_class_name);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000235 return 0;
236 }
237
238 // We have an identifier; check whether it is actually a type.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000239 TypeTy *Type = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope, SS);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000240 if (!Type) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000241 Diag(Tok, diag::err_expected_class_name);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000242 return 0;
243 }
244
245 // Consume the identifier.
246 ConsumeToken();
247
248 return Type;
249}
250
Douglas Gregorec93f442008-04-13 21:30:24 +0000251/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
252/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
253/// until we reach the start of a definition or see a token that
254/// cannot start a definition.
255///
256/// class-specifier: [C++ class]
257/// class-head '{' member-specification[opt] '}'
258/// class-head '{' member-specification[opt] '}' attributes[opt]
259/// class-head:
260/// class-key identifier[opt] base-clause[opt]
261/// class-key nested-name-specifier identifier base-clause[opt]
262/// class-key nested-name-specifier[opt] simple-template-id
263/// base-clause[opt]
264/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
265/// [GNU] class-key attributes[opt] nested-name-specifier
266/// identifier base-clause[opt]
267/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
268/// simple-template-id base-clause[opt]
269/// class-key:
270/// 'class'
271/// 'struct'
272/// 'union'
273///
274/// elaborated-type-specifier: [C++ dcl.type.elab]
275/// class-key ::[opt] nested-name-specifier[opt] identifier
276/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
277/// simple-template-id
278///
279/// Note that the C++ class-specifier and elaborated-type-specifier,
280/// together, subsume the C99 struct-or-union-specifier:
281///
282/// struct-or-union-specifier: [C99 6.7.2.1]
283/// struct-or-union identifier[opt] '{' struct-contents '}'
284/// struct-or-union identifier
285/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
286/// '}' attributes[opt]
287/// [GNU] struct-or-union attributes[opt] identifier
288/// struct-or-union:
289/// 'struct'
290/// 'union'
Douglas Gregor52473432008-12-24 02:52:09 +0000291void Parser::ParseClassSpecifier(DeclSpec &DS,
292 TemplateParameterLists *TemplateParams) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000293 assert((Tok.is(tok::kw_class) ||
294 Tok.is(tok::kw_struct) ||
295 Tok.is(tok::kw_union)) &&
296 "Not a class specifier");
297 DeclSpec::TST TagType =
298 Tok.is(tok::kw_class) ? DeclSpec::TST_class :
299 Tok.is(tok::kw_struct) ? DeclSpec::TST_struct :
300 DeclSpec::TST_union;
301
302 SourceLocation StartLoc = ConsumeToken();
303
304 AttributeList *Attr = 0;
305 // If attributes exist after tag, parse them.
306 if (Tok.is(tok::kw___attribute))
307 Attr = ParseAttributes();
308
Steve Naroffc5ab14f2008-12-24 20:59:21 +0000309 // If declspecs exist after tag, parse them.
310 if (Tok.is(tok::kw___declspec) && PP.getLangOptions().Microsoft)
311 FuzzyParseMicrosoftDeclSpec();
312
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000313 // Parse the (optional) nested-name-specifier.
314 CXXScopeSpec SS;
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +0000315 if (getLang().CPlusPlus && MaybeParseCXXScopeSpecifier(SS)) {
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000316 if (Tok.isNot(tok::identifier))
317 Diag(Tok, diag::err_expected_ident);
318 }
Douglas Gregorec93f442008-04-13 21:30:24 +0000319
320 // Parse the (optional) class name.
321 // FIXME: Alternatively, parse a simple-template-id.
322 IdentifierInfo *Name = 0;
323 SourceLocation NameLoc;
324 if (Tok.is(tok::identifier)) {
325 Name = Tok.getIdentifierInfo();
326 NameLoc = ConsumeToken();
327 }
328
329 // There are three options here. If we have 'struct foo;', then
330 // this is a forward declaration. If we have 'struct foo {...' or
331 // 'struct fo :...' then this is a definition. Otherwise we have
332 // something like 'struct foo xyz', a reference.
333 Action::TagKind TK;
334 if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon)))
335 TK = Action::TK_Definition;
336 else if (Tok.is(tok::semi))
337 TK = Action::TK_Declaration;
338 else
339 TK = Action::TK_Reference;
340
341 if (!Name && TK != Action::TK_Definition) {
342 // We have a declaration or reference to an anonymous class.
Chris Lattnerf006a222008-11-18 07:48:38 +0000343 Diag(StartLoc, diag::err_anon_type_definition)
344 << DeclSpec::getSpecifierName(TagType);
Douglas Gregorec93f442008-04-13 21:30:24 +0000345
346 // Skip the rest of this declarator, up until the comma or semicolon.
347 SkipUntil(tok::comma, true);
348 return;
349 }
350
351 // Parse the tag portion of this.
Douglas Gregor52473432008-12-24 02:52:09 +0000352 DeclTy *TagDecl
353 = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, SS, Name,
354 NameLoc, Attr,
355 Action::MultiTemplateParamsArg(
356 Actions,
357 TemplateParams? &(*TemplateParams)[0] : 0,
358 TemplateParams? TemplateParams->size() : 0));
Douglas Gregorec93f442008-04-13 21:30:24 +0000359
360 // Parse the optional base clause (C++ only).
361 if (getLang().CPlusPlus && Tok.is(tok::colon)) {
362 ParseBaseClause(TagDecl);
363 }
364
365 // If there is a body, parse it and inform the actions module.
366 if (Tok.is(tok::l_brace))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000367 if (getLang().CPlusPlus)
368 ParseCXXMemberSpecification(StartLoc, TagType, TagDecl);
369 else
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000370 ParseStructUnionBody(StartLoc, TagType, TagDecl);
Douglas Gregorec93f442008-04-13 21:30:24 +0000371 else if (TK == Action::TK_Definition) {
372 // FIXME: Complain that we have a base-specifier list but no
373 // definition.
Chris Lattnerf006a222008-11-18 07:48:38 +0000374 Diag(Tok, diag::err_expected_lbrace);
Douglas Gregorec93f442008-04-13 21:30:24 +0000375 }
376
377 const char *PrevSpec = 0;
378 if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, TagDecl))
Chris Lattnerf006a222008-11-18 07:48:38 +0000379 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
Douglas Gregorec93f442008-04-13 21:30:24 +0000380}
381
382/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
383///
384/// base-clause : [C++ class.derived]
385/// ':' base-specifier-list
386/// base-specifier-list:
387/// base-specifier '...'[opt]
388/// base-specifier-list ',' base-specifier '...'[opt]
389void Parser::ParseBaseClause(DeclTy *ClassDecl)
390{
391 assert(Tok.is(tok::colon) && "Not a base clause");
392 ConsumeToken();
393
Douglas Gregorabed2172008-10-22 17:49:05 +0000394 // Build up an array of parsed base specifiers.
395 llvm::SmallVector<BaseTy *, 8> BaseInfo;
396
Douglas Gregorec93f442008-04-13 21:30:24 +0000397 while (true) {
398 // Parse a base-specifier.
Douglas Gregorabed2172008-10-22 17:49:05 +0000399 BaseResult Result = ParseBaseSpecifier(ClassDecl);
400 if (Result.isInvalid) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000401 // Skip the rest of this base specifier, up until the comma or
402 // opening brace.
Douglas Gregorabed2172008-10-22 17:49:05 +0000403 SkipUntil(tok::comma, tok::l_brace, true, true);
404 } else {
405 // Add this to our array of base specifiers.
406 BaseInfo.push_back(Result.Val);
Douglas Gregorec93f442008-04-13 21:30:24 +0000407 }
408
409 // If the next token is a comma, consume it and keep reading
410 // base-specifiers.
411 if (Tok.isNot(tok::comma)) break;
412
413 // Consume the comma.
414 ConsumeToken();
415 }
Douglas Gregorabed2172008-10-22 17:49:05 +0000416
417 // Attach the base specifiers
418 Actions.ActOnBaseSpecifiers(ClassDecl, &BaseInfo[0], BaseInfo.size());
Douglas Gregorec93f442008-04-13 21:30:24 +0000419}
420
421/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
422/// one entry in the base class list of a class specifier, for example:
423/// class foo : public bar, virtual private baz {
424/// 'public bar' and 'virtual private baz' are each base-specifiers.
425///
426/// base-specifier: [C++ class.derived]
427/// ::[opt] nested-name-specifier[opt] class-name
428/// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
429/// class-name
430/// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
431/// class-name
Douglas Gregorabed2172008-10-22 17:49:05 +0000432Parser::BaseResult Parser::ParseBaseSpecifier(DeclTy *ClassDecl)
Douglas Gregorec93f442008-04-13 21:30:24 +0000433{
434 bool IsVirtual = false;
435 SourceLocation StartLoc = Tok.getLocation();
436
437 // Parse the 'virtual' keyword.
438 if (Tok.is(tok::kw_virtual)) {
439 ConsumeToken();
440 IsVirtual = true;
441 }
442
443 // Parse an (optional) access specifier.
444 AccessSpecifier Access = getAccessSpecifierIfPresent();
445 if (Access)
446 ConsumeToken();
447
448 // Parse the 'virtual' keyword (again!), in case it came after the
449 // access specifier.
450 if (Tok.is(tok::kw_virtual)) {
451 SourceLocation VirtualLoc = ConsumeToken();
452 if (IsVirtual) {
453 // Complain about duplicate 'virtual'
Chris Lattnerf006a222008-11-18 07:48:38 +0000454 Diag(VirtualLoc, diag::err_dup_virtual)
455 << SourceRange(VirtualLoc, VirtualLoc);
Douglas Gregorec93f442008-04-13 21:30:24 +0000456 }
457
458 IsVirtual = true;
459 }
460
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000461 // Parse optional '::' and optional nested-name-specifier.
462 CXXScopeSpec SS;
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +0000463 MaybeParseCXXScopeSpecifier(SS);
Douglas Gregorec93f442008-04-13 21:30:24 +0000464
Douglas Gregorec93f442008-04-13 21:30:24 +0000465 // The location of the base class itself.
466 SourceLocation BaseLoc = Tok.getLocation();
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000467
468 // Parse the class-name.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000469 TypeTy *BaseType = ParseClassName(&SS);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000470 if (!BaseType)
471 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000472
473 // Find the complete source range for the base-specifier.
474 SourceRange Range(StartLoc, BaseLoc);
475
Douglas Gregorec93f442008-04-13 21:30:24 +0000476 // Notify semantic analysis that we have parsed a complete
477 // base-specifier.
Sebastian Redl6008ac32008-11-25 22:21:31 +0000478 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
479 BaseType, BaseLoc);
Douglas Gregorec93f442008-04-13 21:30:24 +0000480}
481
482/// getAccessSpecifierIfPresent - Determine whether the next token is
483/// a C++ access-specifier.
484///
485/// access-specifier: [C++ class.derived]
486/// 'private'
487/// 'protected'
488/// 'public'
Douglas Gregor696be932008-04-14 00:13:42 +0000489AccessSpecifier Parser::getAccessSpecifierIfPresent() const
Douglas Gregorec93f442008-04-13 21:30:24 +0000490{
491 switch (Tok.getKind()) {
492 default: return AS_none;
493 case tok::kw_private: return AS_private;
494 case tok::kw_protected: return AS_protected;
495 case tok::kw_public: return AS_public;
496 }
497}
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000498
499/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
500///
501/// member-declaration:
502/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
503/// function-definition ';'[opt]
504/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
505/// using-declaration [TODO]
506/// [C++0x] static_assert-declaration [TODO]
507/// template-declaration [TODO]
Chris Lattnerf3375de2008-12-18 01:12:00 +0000508/// [GNU] '__extension__' member-declaration
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000509///
510/// member-declarator-list:
511/// member-declarator
512/// member-declarator-list ',' member-declarator
513///
514/// member-declarator:
515/// declarator pure-specifier[opt]
516/// declarator constant-initializer[opt]
517/// identifier[opt] ':' constant-expression
518///
519/// pure-specifier: [TODO]
520/// '= 0'
521///
522/// constant-initializer:
523/// '=' constant-expression
524///
525Parser::DeclTy *Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) {
Chris Lattnerf3375de2008-12-18 01:12:00 +0000526 // Handle: member-declaration ::= '__extension__' member-declaration
527 if (Tok.is(tok::kw___extension__)) {
528 // __extension__ silences extension warnings in the subexpression.
529 ExtensionRAIIObject O(Diags); // Use RAII to do this.
530 ConsumeToken();
531 return ParseCXXClassMemberDeclaration(AS);
532 }
533
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000534 SourceLocation DSStart = Tok.getLocation();
535 // decl-specifier-seq:
536 // Parse the common declaration-specifiers piece.
537 DeclSpec DS;
538 ParseDeclarationSpecifiers(DS);
539
540 if (Tok.is(tok::semi)) {
541 ConsumeToken();
542 // C++ 9.2p7: The member-declarator-list can be omitted only after a
543 // class-specifier or an enum-specifier or in a friend declaration.
544 // FIXME: Friend declarations.
545 switch (DS.getTypeSpecType()) {
546 case DeclSpec::TST_struct:
547 case DeclSpec::TST_union:
548 case DeclSpec::TST_class:
549 case DeclSpec::TST_enum:
550 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
551 default:
552 Diag(DSStart, diag::err_no_declarators);
553 return 0;
554 }
555 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000556
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000557 Declarator DeclaratorInfo(DS, Declarator::MemberContext);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000558
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000559 if (Tok.isNot(tok::colon)) {
560 // Parse the first declarator.
561 ParseDeclarator(DeclaratorInfo);
562 // Error parsing the declarator?
Douglas Gregor6704b312008-11-17 22:58:34 +0000563 if (!DeclaratorInfo.hasName()) {
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000564 // If so, skip until the semi-colon or a }.
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000565 SkipUntil(tok::r_brace, true);
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000566 if (Tok.is(tok::semi))
567 ConsumeToken();
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000568 return 0;
569 }
570
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000571 // function-definition:
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000572 if (Tok.is(tok::l_brace)
573 || (DeclaratorInfo.isFunctionDeclarator() && Tok.is(tok::colon))) {
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000574 if (!DeclaratorInfo.isFunctionDeclarator()) {
575 Diag(Tok, diag::err_func_def_no_params);
576 ConsumeBrace();
577 SkipUntil(tok::r_brace, true);
578 return 0;
579 }
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000580
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000581 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
582 Diag(Tok, diag::err_function_declared_typedef);
583 // This recovery skips the entire function body. It would be nice
584 // to simply call ParseCXXInlineMethodDef() below, however Sema
585 // assumes the declarator represents a function, not a typedef.
586 ConsumeBrace();
587 SkipUntil(tok::r_brace, true);
588 return 0;
589 }
590
591 return ParseCXXInlineMethodDef(AS, DeclaratorInfo);
592 }
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000593 }
594
595 // member-declarator-list:
596 // member-declarator
597 // member-declarator-list ',' member-declarator
598
599 DeclTy *LastDeclInGroup = 0;
Sebastian Redl62261042008-12-09 20:22:58 +0000600 OwningExprResult BitfieldSize(Actions);
601 OwningExprResult Init(Actions);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000602
603 while (1) {
604
605 // member-declarator:
606 // declarator pure-specifier[opt]
607 // declarator constant-initializer[opt]
608 // identifier[opt] ':' constant-expression
609
610 if (Tok.is(tok::colon)) {
611 ConsumeToken();
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000612 BitfieldSize = ParseConstantExpression();
613 if (BitfieldSize.isInvalid())
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000614 SkipUntil(tok::comma, true, true);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000615 }
616
617 // pure-specifier:
618 // '= 0'
619 //
620 // constant-initializer:
621 // '=' constant-expression
622
623 if (Tok.is(tok::equal)) {
624 ConsumeToken();
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000625 Init = ParseInitializer();
626 if (Init.isInvalid())
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000627 SkipUntil(tok::comma, true, true);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000628 }
629
630 // If attributes exist after the declarator, parse them.
631 if (Tok.is(tok::kw___attribute))
632 DeclaratorInfo.AddAttributes(ParseAttributes());
633
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000634 // NOTE: If Sema is the Action module and declarator is an instance field,
635 // this call will *not* return the created decl; LastDeclInGroup will be
636 // returned instead.
637 // See Sema::ActOnCXXMemberDeclarator for details.
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000638 LastDeclInGroup = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
639 DeclaratorInfo,
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000640 BitfieldSize.release(),
641 Init.release(),
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000642 LastDeclInGroup);
643
Douglas Gregor605de8d2008-12-16 21:30:33 +0000644 if (DeclaratorInfo.isFunctionDeclarator() &&
645 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
646 != DeclSpec::SCS_typedef) {
647 // We just declared a member function. If this member function
648 // has any default arguments, we'll need to parse them later.
649 LateParsedMethodDeclaration *LateMethod = 0;
650 DeclaratorChunk::FunctionTypeInfo &FTI
651 = DeclaratorInfo.getTypeObject(0).Fun;
652 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
653 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
654 if (!LateMethod) {
655 // Push this method onto the stack of late-parsed method
656 // declarations.
657 getCurTopClassStack().MethodDecls.push_back(
658 LateParsedMethodDeclaration(LastDeclInGroup));
659 LateMethod = &getCurTopClassStack().MethodDecls.back();
660
661 // Add all of the parameters prior to this one (they don't
662 // have default arguments).
663 LateMethod->DefaultArgs.reserve(FTI.NumArgs);
664 for (unsigned I = 0; I < ParamIdx; ++I)
665 LateMethod->DefaultArgs.push_back(
666 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param));
667 }
668
669 // Add this parameter to the list of parameters (it or may
670 // not have a default argument).
671 LateMethod->DefaultArgs.push_back(
672 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
673 FTI.ArgInfo[ParamIdx].DefaultArgTokens));
674 }
675 }
676 }
677
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000678 // If we don't have a comma, it is either the end of the list (a ';')
679 // or an error, bail out.
680 if (Tok.isNot(tok::comma))
681 break;
682
683 // Consume the comma.
684 ConsumeToken();
685
686 // Parse the next declarator.
687 DeclaratorInfo.clear();
Sebastian Redl62261042008-12-09 20:22:58 +0000688 BitfieldSize = 0;
689 Init = 0;
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000690
691 // Attributes are only allowed on the second declarator.
692 if (Tok.is(tok::kw___attribute))
693 DeclaratorInfo.AddAttributes(ParseAttributes());
694
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000695 if (Tok.isNot(tok::colon))
696 ParseDeclarator(DeclaratorInfo);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000697 }
698
699 if (Tok.is(tok::semi)) {
700 ConsumeToken();
701 // Reverse the chain list.
702 return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
703 }
704
705 Diag(Tok, diag::err_expected_semi_decl_list);
706 // Skip to end of block or statement
707 SkipUntil(tok::r_brace, true, true);
708 if (Tok.is(tok::semi))
709 ConsumeToken();
710 return 0;
711}
712
713/// ParseCXXMemberSpecification - Parse the class definition.
714///
715/// member-specification:
716/// member-declaration member-specification[opt]
717/// access-specifier ':' member-specification[opt]
718///
719void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
720 unsigned TagType, DeclTy *TagDecl) {
Sanjiv Guptafa451432008-10-31 09:52:39 +0000721 assert((TagType == DeclSpec::TST_struct ||
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000722 TagType == DeclSpec::TST_union ||
Sanjiv Guptafa451432008-10-31 09:52:39 +0000723 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000724
725 SourceLocation LBraceLoc = ConsumeBrace();
726
727 if (!CurScope->isCXXClassScope() && // Not about to define a nested class.
728 CurScope->isInCXXInlineMethodScope()) {
729 // We will define a local class of an inline method.
730 // Push a new LexedMethodsForTopClass for its inline methods.
731 PushTopClassStack();
732 }
733
734 // Enter a scope for the class.
Douglas Gregor95d40792008-12-10 06:34:36 +0000735 ParseScope ClassScope(this, Scope::CXXClassScope|Scope::DeclScope);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000736
737 Actions.ActOnStartCXXClassDef(CurScope, TagDecl, LBraceLoc);
738
739 // C++ 11p3: Members of a class defined with the keyword class are private
740 // by default. Members of a class defined with the keywords struct or union
741 // are public by default.
742 AccessSpecifier CurAS;
743 if (TagType == DeclSpec::TST_class)
744 CurAS = AS_private;
745 else
746 CurAS = AS_public;
747
748 // While we still have something to read, read the member-declarations.
749 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
750 // Each iteration of this loop reads one member-declaration.
751
752 // Check for extraneous top-level semicolon.
753 if (Tok.is(tok::semi)) {
754 Diag(Tok, diag::ext_extra_struct_semi);
755 ConsumeToken();
756 continue;
757 }
758
759 AccessSpecifier AS = getAccessSpecifierIfPresent();
760 if (AS != AS_none) {
761 // Current token is a C++ access specifier.
762 CurAS = AS;
763 ConsumeToken();
764 ExpectAndConsume(tok::colon, diag::err_expected_colon);
765 continue;
766 }
767
768 // Parse all the comma separated declarators.
769 ParseCXXClassMemberDeclaration(CurAS);
770 }
771
772 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
773
774 AttributeList *AttrList = 0;
775 // If attributes exist after class contents, parse them.
776 if (Tok.is(tok::kw___attribute))
777 AttrList = ParseAttributes(); // FIXME: where should I put them?
778
779 Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
780 LBraceLoc, RBraceLoc);
781
782 // C++ 9.2p2: Within the class member-specification, the class is regarded as
783 // complete within function bodies, default arguments,
784 // exception-specifications, and constructor ctor-initializers (including
785 // such things in nested classes).
786 //
Douglas Gregor605de8d2008-12-16 21:30:33 +0000787 // FIXME: Only function bodies and constructor ctor-initializers are
788 // parsed correctly, fix the rest.
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000789 if (!CurScope->getParent()->isCXXClassScope()) {
790 // We are not inside a nested class. This class and its nested classes
Douglas Gregor605de8d2008-12-16 21:30:33 +0000791 // are complete and we can parse the delayed portions of method
792 // declarations and the lexed inline method definitions.
793 ParseLexedMethodDeclarations();
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000794 ParseLexedMethodDefs();
795
796 // For a local class of inline method, pop the LexedMethodsForTopClass that
797 // was previously pushed.
798
Sanjiv Guptafa451432008-10-31 09:52:39 +0000799 assert((CurScope->isInCXXInlineMethodScope() ||
800 TopClassStacks.size() == 1) &&
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000801 "MethodLexers not getting popped properly!");
802 if (CurScope->isInCXXInlineMethodScope())
803 PopTopClassStack();
804 }
805
806 // Leave the class scope.
Douglas Gregor95d40792008-12-10 06:34:36 +0000807 ClassScope.Exit();
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000808
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000809 Actions.ActOnFinishCXXClassDef(TagDecl);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000810}
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000811
812/// ParseConstructorInitializer - Parse a C++ constructor initializer,
813/// which explicitly initializes the members or base classes of a
814/// class (C++ [class.base.init]). For example, the three initializers
815/// after the ':' in the Derived constructor below:
816///
817/// @code
818/// class Base { };
819/// class Derived : Base {
820/// int x;
821/// float f;
822/// public:
823/// Derived(float f) : Base(), x(17), f(f) { }
824/// };
825/// @endcode
826///
827/// [C++] ctor-initializer:
828/// ':' mem-initializer-list
829///
830/// [C++] mem-initializer-list:
831/// mem-initializer
832/// mem-initializer , mem-initializer-list
833void Parser::ParseConstructorInitializer(DeclTy *ConstructorDecl) {
834 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
835
836 SourceLocation ColonLoc = ConsumeToken();
837
838 llvm::SmallVector<MemInitTy*, 4> MemInitializers;
839
840 do {
841 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
842 if (!MemInit.isInvalid)
843 MemInitializers.push_back(MemInit.Val);
844
845 if (Tok.is(tok::comma))
846 ConsumeToken();
847 else if (Tok.is(tok::l_brace))
848 break;
849 else {
850 // Skip over garbage, until we get to '{'. Don't eat the '{'.
851 SkipUntil(tok::l_brace, true, true);
852 break;
853 }
854 } while (true);
855
856 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
857 &MemInitializers[0], MemInitializers.size());
858}
859
860/// ParseMemInitializer - Parse a C++ member initializer, which is
861/// part of a constructor initializer that explicitly initializes one
862/// member or base class (C++ [class.base.init]). See
863/// ParseConstructorInitializer for an example.
864///
865/// [C++] mem-initializer:
866/// mem-initializer-id '(' expression-list[opt] ')'
867///
868/// [C++] mem-initializer-id:
869/// '::'[opt] nested-name-specifier[opt] class-name
870/// identifier
871Parser::MemInitResult Parser::ParseMemInitializer(DeclTy *ConstructorDecl) {
872 // FIXME: parse '::'[opt] nested-name-specifier[opt]
873
874 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000875 Diag(Tok, diag::err_expected_member_or_base_name);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000876 return true;
877 }
878
879 // Get the identifier. This may be a member name or a class name,
880 // but we'll let the semantic analysis determine which it is.
881 IdentifierInfo *II = Tok.getIdentifierInfo();
882 SourceLocation IdLoc = ConsumeToken();
883
884 // Parse the '('.
885 if (Tok.isNot(tok::l_paren)) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000886 Diag(Tok, diag::err_expected_lparen);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000887 return true;
888 }
889 SourceLocation LParenLoc = ConsumeParen();
890
891 // Parse the optional expression-list.
Sebastian Redl6008ac32008-11-25 22:21:31 +0000892 ExprVector ArgExprs(Actions);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000893 CommaLocsTy CommaLocs;
894 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
895 SkipUntil(tok::r_paren);
896 return true;
897 }
898
899 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
900
Sebastian Redl6008ac32008-11-25 22:21:31 +0000901 return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, II, IdLoc,
902 LParenLoc, ArgExprs.take(),
903 ArgExprs.size(), &CommaLocs[0], RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000904}
Douglas Gregor90a2c972008-11-25 03:22:00 +0000905
906/// ParseExceptionSpecification - Parse a C++ exception-specification
907/// (C++ [except.spec]).
908///
Douglas Gregor9ed9ac82008-12-01 18:00:20 +0000909/// exception-specification:
910/// 'throw' '(' type-id-list [opt] ')'
911/// [MS] 'throw' '(' '...' ')'
Douglas Gregor90a2c972008-11-25 03:22:00 +0000912///
Douglas Gregor9ed9ac82008-12-01 18:00:20 +0000913/// type-id-list:
914/// type-id
915/// type-id-list ',' type-id
Douglas Gregor90a2c972008-11-25 03:22:00 +0000916///
917bool Parser::ParseExceptionSpecification() {
918 assert(Tok.is(tok::kw_throw) && "expected throw");
919
920 SourceLocation ThrowLoc = ConsumeToken();
921
922 if (!Tok.is(tok::l_paren)) {
923 return Diag(Tok, diag::err_expected_lparen_after) << "throw";
924 }
925 SourceLocation LParenLoc = ConsumeParen();
926
Douglas Gregor9ed9ac82008-12-01 18:00:20 +0000927 // Parse throw(...), a Microsoft extension that means "this function
928 // can throw anything".
929 if (Tok.is(tok::ellipsis)) {
930 SourceLocation EllipsisLoc = ConsumeToken();
931 if (!getLang().Microsoft)
932 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
933 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
934 return false;
935 }
936
Douglas Gregor90a2c972008-11-25 03:22:00 +0000937 // Parse the sequence of type-ids.
938 while (Tok.isNot(tok::r_paren)) {
939 ParseTypeName();
940 if (Tok.is(tok::comma))
941 ConsumeToken();
942 else
943 break;
944 }
945
946 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
947 return false;
948}