blob: eaada1c26cb7be5ad5a87ba6d94cf1a930884ec1 [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();
111 DeclTy *D = 0;
Chris Lattner806a5f52008-01-12 07:05:38 +0000112
113 if (Tok.isNot(tok::l_brace)) {
Douglas Gregor61818c52008-11-21 16:10:08 +0000114 D = ParseDeclarationOrFunctionDefinition();
Douglas Gregorad17e372008-12-16 22:23:02 +0000115 if (D)
116 return Actions.ActOnLinkageSpec(Loc, LangBufPtr, StrSize, D);
Chris Lattner806a5f52008-01-12 07:05:38 +0000117
Douglas Gregorad17e372008-12-16 22:23:02 +0000118 return 0;
119 }
120
121 SourceLocation LBrace = ConsumeBrace();
122 llvm::SmallVector<DeclTy *, 8> InnerDecls;
123 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
124 D = ParseExternalDeclaration();
125 if (D)
126 InnerDecls.push_back(D);
Chris Lattner806a5f52008-01-12 07:05:38 +0000127 }
128
Douglas Gregorad17e372008-12-16 22:23:02 +0000129 SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
130 return Actions.ActOnLinkageSpec(Loc, LBrace, RBrace, LangBufPtr, StrSize,
131 &InnerDecls.front(), InnerDecls.size());
Chris Lattner806a5f52008-01-12 07:05:38 +0000132}
Douglas Gregorec93f442008-04-13 21:30:24 +0000133
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000134/// ParseClassName - Parse a C++ class-name, which names a class. Note
135/// that we only check that the result names a type; semantic analysis
136/// will need to verify that the type names a class. The result is
137/// either a type or NULL, dependending on whether a type name was
138/// found.
139///
140/// class-name: [C++ 9.1]
141/// identifier
142/// template-id [TODO]
143///
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000144Parser::TypeTy *Parser::ParseClassName(const CXXScopeSpec *SS) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000145 // Parse the class-name.
146 // FIXME: Alternatively, parse a simple-template-id.
147 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000148 Diag(Tok, diag::err_expected_class_name);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000149 return 0;
150 }
151
152 // We have an identifier; check whether it is actually a type.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000153 TypeTy *Type = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope, SS);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000154 if (!Type) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000155 Diag(Tok, diag::err_expected_class_name);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000156 return 0;
157 }
158
159 // Consume the identifier.
160 ConsumeToken();
161
162 return Type;
163}
164
Douglas Gregorec93f442008-04-13 21:30:24 +0000165/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
166/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
167/// until we reach the start of a definition or see a token that
168/// cannot start a definition.
169///
170/// class-specifier: [C++ class]
171/// class-head '{' member-specification[opt] '}'
172/// class-head '{' member-specification[opt] '}' attributes[opt]
173/// class-head:
174/// class-key identifier[opt] base-clause[opt]
175/// class-key nested-name-specifier identifier base-clause[opt]
176/// class-key nested-name-specifier[opt] simple-template-id
177/// base-clause[opt]
178/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
179/// [GNU] class-key attributes[opt] nested-name-specifier
180/// identifier base-clause[opt]
181/// [GNU] class-key attributes[opt] nested-name-specifier[opt]
182/// simple-template-id base-clause[opt]
183/// class-key:
184/// 'class'
185/// 'struct'
186/// 'union'
187///
188/// elaborated-type-specifier: [C++ dcl.type.elab]
189/// class-key ::[opt] nested-name-specifier[opt] identifier
190/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
191/// simple-template-id
192///
193/// Note that the C++ class-specifier and elaborated-type-specifier,
194/// together, subsume the C99 struct-or-union-specifier:
195///
196/// struct-or-union-specifier: [C99 6.7.2.1]
197/// struct-or-union identifier[opt] '{' struct-contents '}'
198/// struct-or-union identifier
199/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
200/// '}' attributes[opt]
201/// [GNU] struct-or-union attributes[opt] identifier
202/// struct-or-union:
203/// 'struct'
204/// 'union'
205void Parser::ParseClassSpecifier(DeclSpec &DS) {
206 assert((Tok.is(tok::kw_class) ||
207 Tok.is(tok::kw_struct) ||
208 Tok.is(tok::kw_union)) &&
209 "Not a class specifier");
210 DeclSpec::TST TagType =
211 Tok.is(tok::kw_class) ? DeclSpec::TST_class :
212 Tok.is(tok::kw_struct) ? DeclSpec::TST_struct :
213 DeclSpec::TST_union;
214
215 SourceLocation StartLoc = ConsumeToken();
216
217 AttributeList *Attr = 0;
218 // If attributes exist after tag, parse them.
219 if (Tok.is(tok::kw___attribute))
220 Attr = ParseAttributes();
221
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000222 // Parse the (optional) nested-name-specifier.
223 CXXScopeSpec SS;
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +0000224 if (getLang().CPlusPlus && MaybeParseCXXScopeSpecifier(SS)) {
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000225 if (Tok.isNot(tok::identifier))
226 Diag(Tok, diag::err_expected_ident);
227 }
Douglas Gregorec93f442008-04-13 21:30:24 +0000228
229 // Parse the (optional) class name.
230 // FIXME: Alternatively, parse a simple-template-id.
231 IdentifierInfo *Name = 0;
232 SourceLocation NameLoc;
233 if (Tok.is(tok::identifier)) {
234 Name = Tok.getIdentifierInfo();
235 NameLoc = ConsumeToken();
236 }
237
238 // There are three options here. If we have 'struct foo;', then
239 // this is a forward declaration. If we have 'struct foo {...' or
240 // 'struct fo :...' then this is a definition. Otherwise we have
241 // something like 'struct foo xyz', a reference.
242 Action::TagKind TK;
243 if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon)))
244 TK = Action::TK_Definition;
245 else if (Tok.is(tok::semi))
246 TK = Action::TK_Declaration;
247 else
248 TK = Action::TK_Reference;
249
250 if (!Name && TK != Action::TK_Definition) {
251 // We have a declaration or reference to an anonymous class.
Chris Lattnerf006a222008-11-18 07:48:38 +0000252 Diag(StartLoc, diag::err_anon_type_definition)
253 << DeclSpec::getSpecifierName(TagType);
Douglas Gregorec93f442008-04-13 21:30:24 +0000254
255 // Skip the rest of this declarator, up until the comma or semicolon.
256 SkipUntil(tok::comma, true);
257 return;
258 }
259
260 // Parse the tag portion of this.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000261 DeclTy *TagDecl = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, SS, Name,
Douglas Gregorec93f442008-04-13 21:30:24 +0000262 NameLoc, Attr);
263
264 // Parse the optional base clause (C++ only).
265 if (getLang().CPlusPlus && Tok.is(tok::colon)) {
266 ParseBaseClause(TagDecl);
267 }
268
269 // If there is a body, parse it and inform the actions module.
270 if (Tok.is(tok::l_brace))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000271 if (getLang().CPlusPlus)
272 ParseCXXMemberSpecification(StartLoc, TagType, TagDecl);
273 else
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000274 ParseStructUnionBody(StartLoc, TagType, TagDecl);
Douglas Gregorec93f442008-04-13 21:30:24 +0000275 else if (TK == Action::TK_Definition) {
276 // FIXME: Complain that we have a base-specifier list but no
277 // definition.
Chris Lattnerf006a222008-11-18 07:48:38 +0000278 Diag(Tok, diag::err_expected_lbrace);
Douglas Gregorec93f442008-04-13 21:30:24 +0000279 }
280
281 const char *PrevSpec = 0;
282 if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, TagDecl))
Chris Lattnerf006a222008-11-18 07:48:38 +0000283 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
Douglas Gregorec93f442008-04-13 21:30:24 +0000284}
285
286/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
287///
288/// base-clause : [C++ class.derived]
289/// ':' base-specifier-list
290/// base-specifier-list:
291/// base-specifier '...'[opt]
292/// base-specifier-list ',' base-specifier '...'[opt]
293void Parser::ParseBaseClause(DeclTy *ClassDecl)
294{
295 assert(Tok.is(tok::colon) && "Not a base clause");
296 ConsumeToken();
297
Douglas Gregorabed2172008-10-22 17:49:05 +0000298 // Build up an array of parsed base specifiers.
299 llvm::SmallVector<BaseTy *, 8> BaseInfo;
300
Douglas Gregorec93f442008-04-13 21:30:24 +0000301 while (true) {
302 // Parse a base-specifier.
Douglas Gregorabed2172008-10-22 17:49:05 +0000303 BaseResult Result = ParseBaseSpecifier(ClassDecl);
304 if (Result.isInvalid) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000305 // Skip the rest of this base specifier, up until the comma or
306 // opening brace.
Douglas Gregorabed2172008-10-22 17:49:05 +0000307 SkipUntil(tok::comma, tok::l_brace, true, true);
308 } else {
309 // Add this to our array of base specifiers.
310 BaseInfo.push_back(Result.Val);
Douglas Gregorec93f442008-04-13 21:30:24 +0000311 }
312
313 // If the next token is a comma, consume it and keep reading
314 // base-specifiers.
315 if (Tok.isNot(tok::comma)) break;
316
317 // Consume the comma.
318 ConsumeToken();
319 }
Douglas Gregorabed2172008-10-22 17:49:05 +0000320
321 // Attach the base specifiers
322 Actions.ActOnBaseSpecifiers(ClassDecl, &BaseInfo[0], BaseInfo.size());
Douglas Gregorec93f442008-04-13 21:30:24 +0000323}
324
325/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
326/// one entry in the base class list of a class specifier, for example:
327/// class foo : public bar, virtual private baz {
328/// 'public bar' and 'virtual private baz' are each base-specifiers.
329///
330/// base-specifier: [C++ class.derived]
331/// ::[opt] nested-name-specifier[opt] class-name
332/// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
333/// class-name
334/// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
335/// class-name
Douglas Gregorabed2172008-10-22 17:49:05 +0000336Parser::BaseResult Parser::ParseBaseSpecifier(DeclTy *ClassDecl)
Douglas Gregorec93f442008-04-13 21:30:24 +0000337{
338 bool IsVirtual = false;
339 SourceLocation StartLoc = Tok.getLocation();
340
341 // Parse the 'virtual' keyword.
342 if (Tok.is(tok::kw_virtual)) {
343 ConsumeToken();
344 IsVirtual = true;
345 }
346
347 // Parse an (optional) access specifier.
348 AccessSpecifier Access = getAccessSpecifierIfPresent();
349 if (Access)
350 ConsumeToken();
351
352 // Parse the 'virtual' keyword (again!), in case it came after the
353 // access specifier.
354 if (Tok.is(tok::kw_virtual)) {
355 SourceLocation VirtualLoc = ConsumeToken();
356 if (IsVirtual) {
357 // Complain about duplicate 'virtual'
Chris Lattnerf006a222008-11-18 07:48:38 +0000358 Diag(VirtualLoc, diag::err_dup_virtual)
359 << SourceRange(VirtualLoc, VirtualLoc);
Douglas Gregorec93f442008-04-13 21:30:24 +0000360 }
361
362 IsVirtual = true;
363 }
364
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000365 // Parse optional '::' and optional nested-name-specifier.
366 CXXScopeSpec SS;
Argiris Kirtzidis91c80dc2008-11-26 21:41:52 +0000367 MaybeParseCXXScopeSpecifier(SS);
Douglas Gregorec93f442008-04-13 21:30:24 +0000368
Douglas Gregorec93f442008-04-13 21:30:24 +0000369 // The location of the base class itself.
370 SourceLocation BaseLoc = Tok.getLocation();
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000371
372 // Parse the class-name.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000373 TypeTy *BaseType = ParseClassName(&SS);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000374 if (!BaseType)
375 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000376
377 // Find the complete source range for the base-specifier.
378 SourceRange Range(StartLoc, BaseLoc);
379
Douglas Gregorec93f442008-04-13 21:30:24 +0000380 // Notify semantic analysis that we have parsed a complete
381 // base-specifier.
Sebastian Redl6008ac32008-11-25 22:21:31 +0000382 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
383 BaseType, BaseLoc);
Douglas Gregorec93f442008-04-13 21:30:24 +0000384}
385
386/// getAccessSpecifierIfPresent - Determine whether the next token is
387/// a C++ access-specifier.
388///
389/// access-specifier: [C++ class.derived]
390/// 'private'
391/// 'protected'
392/// 'public'
Douglas Gregor696be932008-04-14 00:13:42 +0000393AccessSpecifier Parser::getAccessSpecifierIfPresent() const
Douglas Gregorec93f442008-04-13 21:30:24 +0000394{
395 switch (Tok.getKind()) {
396 default: return AS_none;
397 case tok::kw_private: return AS_private;
398 case tok::kw_protected: return AS_protected;
399 case tok::kw_public: return AS_public;
400 }
401}
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000402
403/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
404///
405/// member-declaration:
406/// decl-specifier-seq[opt] member-declarator-list[opt] ';'
407/// function-definition ';'[opt]
408/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
409/// using-declaration [TODO]
410/// [C++0x] static_assert-declaration [TODO]
411/// template-declaration [TODO]
Chris Lattnerf3375de2008-12-18 01:12:00 +0000412/// [GNU] '__extension__' member-declaration
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000413///
414/// member-declarator-list:
415/// member-declarator
416/// member-declarator-list ',' member-declarator
417///
418/// member-declarator:
419/// declarator pure-specifier[opt]
420/// declarator constant-initializer[opt]
421/// identifier[opt] ':' constant-expression
422///
423/// pure-specifier: [TODO]
424/// '= 0'
425///
426/// constant-initializer:
427/// '=' constant-expression
428///
429Parser::DeclTy *Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) {
Chris Lattnerf3375de2008-12-18 01:12:00 +0000430 // Handle: member-declaration ::= '__extension__' member-declaration
431 if (Tok.is(tok::kw___extension__)) {
432 // __extension__ silences extension warnings in the subexpression.
433 ExtensionRAIIObject O(Diags); // Use RAII to do this.
434 ConsumeToken();
435 return ParseCXXClassMemberDeclaration(AS);
436 }
437
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000438 SourceLocation DSStart = Tok.getLocation();
439 // decl-specifier-seq:
440 // Parse the common declaration-specifiers piece.
441 DeclSpec DS;
442 ParseDeclarationSpecifiers(DS);
443
444 if (Tok.is(tok::semi)) {
445 ConsumeToken();
446 // C++ 9.2p7: The member-declarator-list can be omitted only after a
447 // class-specifier or an enum-specifier or in a friend declaration.
448 // FIXME: Friend declarations.
449 switch (DS.getTypeSpecType()) {
450 case DeclSpec::TST_struct:
451 case DeclSpec::TST_union:
452 case DeclSpec::TST_class:
453 case DeclSpec::TST_enum:
454 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
455 default:
456 Diag(DSStart, diag::err_no_declarators);
457 return 0;
458 }
459 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000460
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000461 Declarator DeclaratorInfo(DS, Declarator::MemberContext);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000462
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000463 if (Tok.isNot(tok::colon)) {
464 // Parse the first declarator.
465 ParseDeclarator(DeclaratorInfo);
466 // Error parsing the declarator?
Douglas Gregor6704b312008-11-17 22:58:34 +0000467 if (!DeclaratorInfo.hasName()) {
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000468 // If so, skip until the semi-colon or a }.
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000469 SkipUntil(tok::r_brace, true);
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000470 if (Tok.is(tok::semi))
471 ConsumeToken();
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000472 return 0;
473 }
474
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000475 // function-definition:
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000476 if (Tok.is(tok::l_brace)
477 || (DeclaratorInfo.isFunctionDeclarator() && Tok.is(tok::colon))) {
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000478 if (!DeclaratorInfo.isFunctionDeclarator()) {
479 Diag(Tok, diag::err_func_def_no_params);
480 ConsumeBrace();
481 SkipUntil(tok::r_brace, true);
482 return 0;
483 }
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000484
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000485 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
486 Diag(Tok, diag::err_function_declared_typedef);
487 // This recovery skips the entire function body. It would be nice
488 // to simply call ParseCXXInlineMethodDef() below, however Sema
489 // assumes the declarator represents a function, not a typedef.
490 ConsumeBrace();
491 SkipUntil(tok::r_brace, true);
492 return 0;
493 }
494
495 return ParseCXXInlineMethodDef(AS, DeclaratorInfo);
496 }
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000497 }
498
499 // member-declarator-list:
500 // member-declarator
501 // member-declarator-list ',' member-declarator
502
503 DeclTy *LastDeclInGroup = 0;
Sebastian Redl62261042008-12-09 20:22:58 +0000504 OwningExprResult BitfieldSize(Actions);
505 OwningExprResult Init(Actions);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000506
507 while (1) {
508
509 // member-declarator:
510 // declarator pure-specifier[opt]
511 // declarator constant-initializer[opt]
512 // identifier[opt] ':' constant-expression
513
514 if (Tok.is(tok::colon)) {
515 ConsumeToken();
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000516 BitfieldSize = ParseConstantExpression();
517 if (BitfieldSize.isInvalid())
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000518 SkipUntil(tok::comma, true, true);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000519 }
520
521 // pure-specifier:
522 // '= 0'
523 //
524 // constant-initializer:
525 // '=' constant-expression
526
527 if (Tok.is(tok::equal)) {
528 ConsumeToken();
Sebastian Redlbb4dae72008-12-09 13:15:23 +0000529 Init = ParseInitializer();
530 if (Init.isInvalid())
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000531 SkipUntil(tok::comma, true, true);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000532 }
533
534 // If attributes exist after the declarator, parse them.
535 if (Tok.is(tok::kw___attribute))
536 DeclaratorInfo.AddAttributes(ParseAttributes());
537
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000538 // NOTE: If Sema is the Action module and declarator is an instance field,
539 // this call will *not* return the created decl; LastDeclInGroup will be
540 // returned instead.
541 // See Sema::ActOnCXXMemberDeclarator for details.
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000542 LastDeclInGroup = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
543 DeclaratorInfo,
Sebastian Redl6f1ee232008-12-10 00:02:53 +0000544 BitfieldSize.release(),
545 Init.release(),
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000546 LastDeclInGroup);
547
Douglas Gregor605de8d2008-12-16 21:30:33 +0000548 if (DeclaratorInfo.isFunctionDeclarator() &&
549 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
550 != DeclSpec::SCS_typedef) {
551 // We just declared a member function. If this member function
552 // has any default arguments, we'll need to parse them later.
553 LateParsedMethodDeclaration *LateMethod = 0;
554 DeclaratorChunk::FunctionTypeInfo &FTI
555 = DeclaratorInfo.getTypeObject(0).Fun;
556 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
557 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
558 if (!LateMethod) {
559 // Push this method onto the stack of late-parsed method
560 // declarations.
561 getCurTopClassStack().MethodDecls.push_back(
562 LateParsedMethodDeclaration(LastDeclInGroup));
563 LateMethod = &getCurTopClassStack().MethodDecls.back();
564
565 // Add all of the parameters prior to this one (they don't
566 // have default arguments).
567 LateMethod->DefaultArgs.reserve(FTI.NumArgs);
568 for (unsigned I = 0; I < ParamIdx; ++I)
569 LateMethod->DefaultArgs.push_back(
570 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param));
571 }
572
573 // Add this parameter to the list of parameters (it or may
574 // not have a default argument).
575 LateMethod->DefaultArgs.push_back(
576 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
577 FTI.ArgInfo[ParamIdx].DefaultArgTokens));
578 }
579 }
580 }
581
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000582 // If we don't have a comma, it is either the end of the list (a ';')
583 // or an error, bail out.
584 if (Tok.isNot(tok::comma))
585 break;
586
587 // Consume the comma.
588 ConsumeToken();
589
590 // Parse the next declarator.
591 DeclaratorInfo.clear();
Sebastian Redl62261042008-12-09 20:22:58 +0000592 BitfieldSize = 0;
593 Init = 0;
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000594
595 // Attributes are only allowed on the second declarator.
596 if (Tok.is(tok::kw___attribute))
597 DeclaratorInfo.AddAttributes(ParseAttributes());
598
Argiris Kirtzidisf8009b42008-06-28 08:10:48 +0000599 if (Tok.isNot(tok::colon))
600 ParseDeclarator(DeclaratorInfo);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000601 }
602
603 if (Tok.is(tok::semi)) {
604 ConsumeToken();
605 // Reverse the chain list.
606 return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
607 }
608
609 Diag(Tok, diag::err_expected_semi_decl_list);
610 // Skip to end of block or statement
611 SkipUntil(tok::r_brace, true, true);
612 if (Tok.is(tok::semi))
613 ConsumeToken();
614 return 0;
615}
616
617/// ParseCXXMemberSpecification - Parse the class definition.
618///
619/// member-specification:
620/// member-declaration member-specification[opt]
621/// access-specifier ':' member-specification[opt]
622///
623void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
624 unsigned TagType, DeclTy *TagDecl) {
Sanjiv Guptafa451432008-10-31 09:52:39 +0000625 assert((TagType == DeclSpec::TST_struct ||
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000626 TagType == DeclSpec::TST_union ||
Sanjiv Guptafa451432008-10-31 09:52:39 +0000627 TagType == DeclSpec::TST_class) && "Invalid TagType!");
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000628
629 SourceLocation LBraceLoc = ConsumeBrace();
630
631 if (!CurScope->isCXXClassScope() && // Not about to define a nested class.
632 CurScope->isInCXXInlineMethodScope()) {
633 // We will define a local class of an inline method.
634 // Push a new LexedMethodsForTopClass for its inline methods.
635 PushTopClassStack();
636 }
637
638 // Enter a scope for the class.
Douglas Gregor95d40792008-12-10 06:34:36 +0000639 ParseScope ClassScope(this, Scope::CXXClassScope|Scope::DeclScope);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000640
641 Actions.ActOnStartCXXClassDef(CurScope, TagDecl, LBraceLoc);
642
643 // C++ 11p3: Members of a class defined with the keyword class are private
644 // by default. Members of a class defined with the keywords struct or union
645 // are public by default.
646 AccessSpecifier CurAS;
647 if (TagType == DeclSpec::TST_class)
648 CurAS = AS_private;
649 else
650 CurAS = AS_public;
651
652 // While we still have something to read, read the member-declarations.
653 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
654 // Each iteration of this loop reads one member-declaration.
655
656 // Check for extraneous top-level semicolon.
657 if (Tok.is(tok::semi)) {
658 Diag(Tok, diag::ext_extra_struct_semi);
659 ConsumeToken();
660 continue;
661 }
662
663 AccessSpecifier AS = getAccessSpecifierIfPresent();
664 if (AS != AS_none) {
665 // Current token is a C++ access specifier.
666 CurAS = AS;
667 ConsumeToken();
668 ExpectAndConsume(tok::colon, diag::err_expected_colon);
669 continue;
670 }
671
672 // Parse all the comma separated declarators.
673 ParseCXXClassMemberDeclaration(CurAS);
674 }
675
676 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
677
678 AttributeList *AttrList = 0;
679 // If attributes exist after class contents, parse them.
680 if (Tok.is(tok::kw___attribute))
681 AttrList = ParseAttributes(); // FIXME: where should I put them?
682
683 Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
684 LBraceLoc, RBraceLoc);
685
686 // C++ 9.2p2: Within the class member-specification, the class is regarded as
687 // complete within function bodies, default arguments,
688 // exception-specifications, and constructor ctor-initializers (including
689 // such things in nested classes).
690 //
Douglas Gregor605de8d2008-12-16 21:30:33 +0000691 // FIXME: Only function bodies and constructor ctor-initializers are
692 // parsed correctly, fix the rest.
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000693 if (!CurScope->getParent()->isCXXClassScope()) {
694 // We are not inside a nested class. This class and its nested classes
Douglas Gregor605de8d2008-12-16 21:30:33 +0000695 // are complete and we can parse the delayed portions of method
696 // declarations and the lexed inline method definitions.
697 ParseLexedMethodDeclarations();
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000698 ParseLexedMethodDefs();
699
700 // For a local class of inline method, pop the LexedMethodsForTopClass that
701 // was previously pushed.
702
Sanjiv Guptafa451432008-10-31 09:52:39 +0000703 assert((CurScope->isInCXXInlineMethodScope() ||
704 TopClassStacks.size() == 1) &&
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000705 "MethodLexers not getting popped properly!");
706 if (CurScope->isInCXXInlineMethodScope())
707 PopTopClassStack();
708 }
709
710 // Leave the class scope.
Douglas Gregor95d40792008-12-10 06:34:36 +0000711 ClassScope.Exit();
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000712
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000713 Actions.ActOnFinishCXXClassDef(TagDecl);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000714}
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000715
716/// ParseConstructorInitializer - Parse a C++ constructor initializer,
717/// which explicitly initializes the members or base classes of a
718/// class (C++ [class.base.init]). For example, the three initializers
719/// after the ':' in the Derived constructor below:
720///
721/// @code
722/// class Base { };
723/// class Derived : Base {
724/// int x;
725/// float f;
726/// public:
727/// Derived(float f) : Base(), x(17), f(f) { }
728/// };
729/// @endcode
730///
731/// [C++] ctor-initializer:
732/// ':' mem-initializer-list
733///
734/// [C++] mem-initializer-list:
735/// mem-initializer
736/// mem-initializer , mem-initializer-list
737void Parser::ParseConstructorInitializer(DeclTy *ConstructorDecl) {
738 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
739
740 SourceLocation ColonLoc = ConsumeToken();
741
742 llvm::SmallVector<MemInitTy*, 4> MemInitializers;
743
744 do {
745 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
746 if (!MemInit.isInvalid)
747 MemInitializers.push_back(MemInit.Val);
748
749 if (Tok.is(tok::comma))
750 ConsumeToken();
751 else if (Tok.is(tok::l_brace))
752 break;
753 else {
754 // Skip over garbage, until we get to '{'. Don't eat the '{'.
755 SkipUntil(tok::l_brace, true, true);
756 break;
757 }
758 } while (true);
759
760 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
761 &MemInitializers[0], MemInitializers.size());
762}
763
764/// ParseMemInitializer - Parse a C++ member initializer, which is
765/// part of a constructor initializer that explicitly initializes one
766/// member or base class (C++ [class.base.init]). See
767/// ParseConstructorInitializer for an example.
768///
769/// [C++] mem-initializer:
770/// mem-initializer-id '(' expression-list[opt] ')'
771///
772/// [C++] mem-initializer-id:
773/// '::'[opt] nested-name-specifier[opt] class-name
774/// identifier
775Parser::MemInitResult Parser::ParseMemInitializer(DeclTy *ConstructorDecl) {
776 // FIXME: parse '::'[opt] nested-name-specifier[opt]
777
778 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000779 Diag(Tok, diag::err_expected_member_or_base_name);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000780 return true;
781 }
782
783 // Get the identifier. This may be a member name or a class name,
784 // but we'll let the semantic analysis determine which it is.
785 IdentifierInfo *II = Tok.getIdentifierInfo();
786 SourceLocation IdLoc = ConsumeToken();
787
788 // Parse the '('.
789 if (Tok.isNot(tok::l_paren)) {
Chris Lattnerf006a222008-11-18 07:48:38 +0000790 Diag(Tok, diag::err_expected_lparen);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000791 return true;
792 }
793 SourceLocation LParenLoc = ConsumeParen();
794
795 // Parse the optional expression-list.
Sebastian Redl6008ac32008-11-25 22:21:31 +0000796 ExprVector ArgExprs(Actions);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000797 CommaLocsTy CommaLocs;
798 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
799 SkipUntil(tok::r_paren);
800 return true;
801 }
802
803 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
804
Sebastian Redl6008ac32008-11-25 22:21:31 +0000805 return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, II, IdLoc,
806 LParenLoc, ArgExprs.take(),
807 ArgExprs.size(), &CommaLocs[0], RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000808}
Douglas Gregor90a2c972008-11-25 03:22:00 +0000809
810/// ParseExceptionSpecification - Parse a C++ exception-specification
811/// (C++ [except.spec]).
812///
Douglas Gregor9ed9ac82008-12-01 18:00:20 +0000813/// exception-specification:
814/// 'throw' '(' type-id-list [opt] ')'
815/// [MS] 'throw' '(' '...' ')'
Douglas Gregor90a2c972008-11-25 03:22:00 +0000816///
Douglas Gregor9ed9ac82008-12-01 18:00:20 +0000817/// type-id-list:
818/// type-id
819/// type-id-list ',' type-id
Douglas Gregor90a2c972008-11-25 03:22:00 +0000820///
821bool Parser::ParseExceptionSpecification() {
822 assert(Tok.is(tok::kw_throw) && "expected throw");
823
824 SourceLocation ThrowLoc = ConsumeToken();
825
826 if (!Tok.is(tok::l_paren)) {
827 return Diag(Tok, diag::err_expected_lparen_after) << "throw";
828 }
829 SourceLocation LParenLoc = ConsumeParen();
830
Douglas Gregor9ed9ac82008-12-01 18:00:20 +0000831 // Parse throw(...), a Microsoft extension that means "this function
832 // can throw anything".
833 if (Tok.is(tok::ellipsis)) {
834 SourceLocation EllipsisLoc = ConsumeToken();
835 if (!getLang().Microsoft)
836 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
837 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
838 return false;
839 }
840
Douglas Gregor90a2c972008-11-25 03:22:00 +0000841 // Parse the sequence of type-ids.
842 while (Tok.isNot(tok::r_paren)) {
843 ParseTypeName();
844 if (Tok.is(tok::comma))
845 ConsumeToken();
846 else
847 break;
848 }
849
850 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
851 return false;
852}