ParseDeclCXX.cpp revision 31fc07df7f0fc89ebf83ca05a20b29de45a7598d
1//===--- ParseDeclCXX.cpp - C++ Declaration Parsing -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the C++ Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "clang/Basic/Diagnostic.h"
16#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Scope.h"
18using namespace clang;
19
20/// ParseNamespace - We know that the current token is a namespace keyword. This
21/// may either be a top level namespace or a block-level namespace alias.
22///
23///       namespace-definition: [C++ 7.3: basic.namespace]
24///         named-namespace-definition
25///         unnamed-namespace-definition
26///
27///       unnamed-namespace-definition:
28///         'namespace' attributes[opt] '{' namespace-body '}'
29///
30///       named-namespace-definition:
31///         original-namespace-definition
32///         extension-namespace-definition
33///
34///       original-namespace-definition:
35///         'namespace' identifier attributes[opt] '{' namespace-body '}'
36///
37///       extension-namespace-definition:
38///         'namespace' original-namespace-name '{' namespace-body '}'
39///
40///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
41///         'namespace' identifier '=' qualified-namespace-specifier ';'
42///
43Parser::DeclTy *Parser::ParseNamespace(unsigned Context) {
44  assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
45  SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
46
47  SourceLocation IdentLoc;
48  IdentifierInfo *Ident = 0;
49
50  if (Tok.is(tok::identifier)) {
51    Ident = Tok.getIdentifierInfo();
52    IdentLoc = ConsumeToken();  // eat the identifier.
53  }
54
55  // Read label attributes, if present.
56  DeclTy *AttrList = 0;
57  if (Tok.is(tok::kw___attribute))
58    // FIXME: save these somewhere.
59    AttrList = ParseAttributes();
60
61  if (Tok.is(tok::equal)) {
62    // FIXME: Verify no attributes were present.
63    // FIXME: parse this.
64  } else if (Tok.is(tok::l_brace)) {
65
66    SourceLocation LBrace = ConsumeBrace();
67
68    // Enter a scope for the namespace.
69    EnterScope(Scope::DeclScope);
70
71    DeclTy *NamespcDecl =
72      Actions.ActOnStartNamespaceDef(CurScope, IdentLoc, Ident, LBrace);
73
74    while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof))
75      ParseExternalDeclaration();
76
77    // Leave the namespace scope.
78    ExitScope();
79
80    SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
81    Actions.ActOnFinishNamespaceDef(NamespcDecl, RBrace);
82
83    return NamespcDecl;
84
85  } else {
86    unsigned D = Ident ? diag::err_expected_lbrace :
87                         diag::err_expected_ident_lbrace;
88    Diag(Tok.getLocation(), D);
89  }
90
91  return 0;
92}
93
94/// ParseLinkage - We know that the current token is a string_literal
95/// and just before that, that extern was seen.
96///
97///       linkage-specification: [C++ 7.5p2: dcl.link]
98///         'extern' string-literal '{' declaration-seq[opt] '}'
99///         'extern' string-literal declaration
100///
101Parser::DeclTy *Parser::ParseLinkage(unsigned Context) {
102  assert(Tok.is(tok::string_literal) && "Not a stringliteral!");
103  llvm::SmallVector<char, 8> LangBuffer;
104  // LangBuffer is guaranteed to be big enough.
105  LangBuffer.resize(Tok.getLength());
106  const char *LangBufPtr = &LangBuffer[0];
107  unsigned StrSize = PP.getSpelling(Tok, LangBufPtr);
108
109  SourceLocation Loc = ConsumeStringToken();
110  DeclTy *D = 0;
111  SourceLocation LBrace, RBrace;
112
113  if (Tok.isNot(tok::l_brace)) {
114    D = ParseDeclaration(Context);
115  } else {
116    LBrace = ConsumeBrace();
117    while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
118      // FIXME capture the decls.
119      D = ParseExternalDeclaration();
120    }
121
122    RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
123  }
124
125  if (!D)
126    return 0;
127
128  return Actions.ActOnLinkageSpec(Loc, LBrace, RBrace, LangBufPtr, StrSize, D);
129}
130
131/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
132/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
133/// until we reach the start of a definition or see a token that
134/// cannot start a definition.
135///
136///       class-specifier: [C++ class]
137///         class-head '{' member-specification[opt] '}'
138///         class-head '{' member-specification[opt] '}' attributes[opt]
139///       class-head:
140///         class-key identifier[opt] base-clause[opt]
141///         class-key nested-name-specifier identifier base-clause[opt]
142///         class-key nested-name-specifier[opt] simple-template-id
143///                          base-clause[opt]
144/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
145/// [GNU]   class-key attributes[opt] nested-name-specifier
146///                          identifier base-clause[opt]
147/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
148///                          simple-template-id base-clause[opt]
149///       class-key:
150///         'class'
151///         'struct'
152///         'union'
153///
154///       elaborated-type-specifier: [C++ dcl.type.elab]
155///         class-key ::[opt] nested-name-specifier[opt] identifier
156///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
157///                          simple-template-id
158///
159///  Note that the C++ class-specifier and elaborated-type-specifier,
160///  together, subsume the C99 struct-or-union-specifier:
161///
162///       struct-or-union-specifier: [C99 6.7.2.1]
163///         struct-or-union identifier[opt] '{' struct-contents '}'
164///         struct-or-union identifier
165/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
166///                                                         '}' attributes[opt]
167/// [GNU]   struct-or-union attributes[opt] identifier
168///       struct-or-union:
169///         'struct'
170///         'union'
171void Parser::ParseClassSpecifier(DeclSpec &DS) {
172  assert((Tok.is(tok::kw_class) ||
173          Tok.is(tok::kw_struct) ||
174          Tok.is(tok::kw_union)) &&
175         "Not a class specifier");
176  DeclSpec::TST TagType =
177    Tok.is(tok::kw_class) ? DeclSpec::TST_class :
178    Tok.is(tok::kw_struct) ? DeclSpec::TST_struct :
179    DeclSpec::TST_union;
180
181  SourceLocation StartLoc = ConsumeToken();
182
183  AttributeList *Attr = 0;
184  // If attributes exist after tag, parse them.
185  if (Tok.is(tok::kw___attribute))
186    Attr = ParseAttributes();
187
188  // FIXME: Parse the (optional) nested-name-specifier.
189
190  // Parse the (optional) class name.
191  // FIXME: Alternatively, parse a simple-template-id.
192  IdentifierInfo *Name = 0;
193  SourceLocation NameLoc;
194  if (Tok.is(tok::identifier)) {
195    Name = Tok.getIdentifierInfo();
196    NameLoc = ConsumeToken();
197  }
198
199  // There are three options here.  If we have 'struct foo;', then
200  // this is a forward declaration.  If we have 'struct foo {...' or
201  // 'struct fo :...' then this is a definition. Otherwise we have
202  // something like 'struct foo xyz', a reference.
203  Action::TagKind TK;
204  if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon)))
205    TK = Action::TK_Definition;
206  else if (Tok.is(tok::semi))
207    TK = Action::TK_Declaration;
208  else
209    TK = Action::TK_Reference;
210
211  if (!Name && TK != Action::TK_Definition) {
212    // We have a declaration or reference to an anonymous class.
213    Diag(StartLoc, diag::err_anon_type_definition,
214         DeclSpec::getSpecifierName(TagType));
215
216    // Skip the rest of this declarator, up until the comma or semicolon.
217    SkipUntil(tok::comma, true);
218    return;
219  }
220
221  // Parse the tag portion of this.
222  DeclTy *TagDecl = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, Name,
223                                     NameLoc, Attr);
224
225  // Parse the optional base clause (C++ only).
226  if (getLang().CPlusPlus && Tok.is(tok::colon)) {
227    ParseBaseClause(TagDecl);
228  }
229
230  // If there is a body, parse it and inform the actions module.
231  if (Tok.is(tok::l_brace))
232    if (getLang().CPlusPlus)
233      ParseCXXMemberSpecification(StartLoc, TagType, TagDecl);
234    else
235      ParseStructUnionBody(StartLoc, TagType, TagDecl);
236  else if (TK == Action::TK_Definition) {
237    // FIXME: Complain that we have a base-specifier list but no
238    // definition.
239    Diag(Tok.getLocation(), diag::err_expected_lbrace);
240  }
241
242  const char *PrevSpec = 0;
243  if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, TagDecl))
244    Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec);
245}
246
247/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
248///
249///       base-clause : [C++ class.derived]
250///         ':' base-specifier-list
251///       base-specifier-list:
252///         base-specifier '...'[opt]
253///         base-specifier-list ',' base-specifier '...'[opt]
254void Parser::ParseBaseClause(DeclTy *ClassDecl)
255{
256  assert(Tok.is(tok::colon) && "Not a base clause");
257  ConsumeToken();
258
259  // Build up an array of parsed base specifiers.
260  llvm::SmallVector<BaseTy *, 8> BaseInfo;
261
262  while (true) {
263    // Parse a base-specifier.
264    BaseResult Result = ParseBaseSpecifier(ClassDecl);
265    if (Result.isInvalid) {
266      // Skip the rest of this base specifier, up until the comma or
267      // opening brace.
268      SkipUntil(tok::comma, tok::l_brace, true, true);
269    } else {
270      // Add this to our array of base specifiers.
271      BaseInfo.push_back(Result.Val);
272    }
273
274    // If the next token is a comma, consume it and keep reading
275    // base-specifiers.
276    if (Tok.isNot(tok::comma)) break;
277
278    // Consume the comma.
279    ConsumeToken();
280  }
281
282  // Attach the base specifiers
283  Actions.ActOnBaseSpecifiers(ClassDecl, &BaseInfo[0], BaseInfo.size());
284}
285
286/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
287/// one entry in the base class list of a class specifier, for example:
288///    class foo : public bar, virtual private baz {
289/// 'public bar' and 'virtual private baz' are each base-specifiers.
290///
291///       base-specifier: [C++ class.derived]
292///         ::[opt] nested-name-specifier[opt] class-name
293///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
294///                        class-name
295///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
296///                        class-name
297Parser::BaseResult Parser::ParseBaseSpecifier(DeclTy *ClassDecl)
298{
299  bool IsVirtual = false;
300  SourceLocation StartLoc = Tok.getLocation();
301
302  // Parse the 'virtual' keyword.
303  if (Tok.is(tok::kw_virtual))  {
304    ConsumeToken();
305    IsVirtual = true;
306  }
307
308  // Parse an (optional) access specifier.
309  AccessSpecifier Access = getAccessSpecifierIfPresent();
310  if (Access)
311    ConsumeToken();
312
313  // Parse the 'virtual' keyword (again!), in case it came after the
314  // access specifier.
315  if (Tok.is(tok::kw_virtual))  {
316    SourceLocation VirtualLoc = ConsumeToken();
317    if (IsVirtual) {
318      // Complain about duplicate 'virtual'
319      Diag(VirtualLoc, diag::err_dup_virtual,
320           SourceRange(VirtualLoc, VirtualLoc));
321    }
322
323    IsVirtual = true;
324  }
325
326  // FIXME: Parse optional '::' and optional nested-name-specifier.
327
328  // Parse the class-name.
329  // FIXME: Alternatively, parse a simple-template-id.
330  if (Tok.isNot(tok::identifier)) {
331    Diag(Tok.getLocation(), diag::err_expected_class_name);
332    return true;
333  }
334
335  // We have an identifier; check whether it is actually a type.
336  TypeTy *BaseType = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope);
337  if (!BaseType) {
338    Diag(Tok.getLocation(), diag::err_expected_class_name);
339    return true;
340  }
341
342  // The location of the base class itself.
343  SourceLocation BaseLoc = Tok.getLocation();
344
345  // Find the complete source range for the base-specifier.
346  SourceRange Range(StartLoc, BaseLoc);
347
348  // Consume the identifier token (finally!).
349  ConsumeToken();
350
351  // Notify semantic analysis that we have parsed a complete
352  // base-specifier.
353  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access, BaseType,
354                                    BaseLoc);
355}
356
357/// getAccessSpecifierIfPresent - Determine whether the next token is
358/// a C++ access-specifier.
359///
360///       access-specifier: [C++ class.derived]
361///         'private'
362///         'protected'
363///         'public'
364AccessSpecifier Parser::getAccessSpecifierIfPresent() const
365{
366  switch (Tok.getKind()) {
367  default: return AS_none;
368  case tok::kw_private: return AS_private;
369  case tok::kw_protected: return AS_protected;
370  case tok::kw_public: return AS_public;
371  }
372}
373
374/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
375///
376///       member-declaration:
377///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
378///         function-definition ';'[opt]
379///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
380///         using-declaration                                            [TODO]
381/// [C++0x] static_assert-declaration                                    [TODO]
382///         template-declaration                                         [TODO]
383///
384///       member-declarator-list:
385///         member-declarator
386///         member-declarator-list ',' member-declarator
387///
388///       member-declarator:
389///         declarator pure-specifier[opt]
390///         declarator constant-initializer[opt]
391///         identifier[opt] ':' constant-expression
392///
393///       pure-specifier:   [TODO]
394///         '= 0'
395///
396///       constant-initializer:
397///         '=' constant-expression
398///
399Parser::DeclTy *Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) {
400  SourceLocation DSStart = Tok.getLocation();
401  // decl-specifier-seq:
402  // Parse the common declaration-specifiers piece.
403  DeclSpec DS;
404  ParseDeclarationSpecifiers(DS);
405
406  if (Tok.is(tok::semi)) {
407    ConsumeToken();
408    // C++ 9.2p7: The member-declarator-list can be omitted only after a
409    // class-specifier or an enum-specifier or in a friend declaration.
410    // FIXME: Friend declarations.
411    switch (DS.getTypeSpecType()) {
412      case DeclSpec::TST_struct:
413      case DeclSpec::TST_union:
414      case DeclSpec::TST_class:
415      case DeclSpec::TST_enum:
416        return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
417      default:
418        Diag(DSStart, diag::err_no_declarators);
419        return 0;
420    }
421  }
422
423  Declarator DeclaratorInfo(DS, Declarator::MemberContext);
424
425  if (Tok.isNot(tok::colon)) {
426    // Parse the first declarator.
427    ParseDeclarator(DeclaratorInfo);
428    // Error parsing the declarator?
429    if (DeclaratorInfo.getIdentifier() == 0) {
430      // If so, skip until the semi-colon or a }.
431      SkipUntil(tok::r_brace, true);
432      if (Tok.is(tok::semi))
433        ConsumeToken();
434      return 0;
435    }
436
437    // function-definition:
438    if (Tok.is(tok::l_brace)) {
439      if (!DeclaratorInfo.isFunctionDeclarator()) {
440        Diag(Tok, diag::err_func_def_no_params);
441        ConsumeBrace();
442        SkipUntil(tok::r_brace, true);
443        return 0;
444      }
445
446      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
447        Diag(Tok, diag::err_function_declared_typedef);
448        // This recovery skips the entire function body. It would be nice
449        // to simply call ParseCXXInlineMethodDef() below, however Sema
450        // assumes the declarator represents a function, not a typedef.
451        ConsumeBrace();
452        SkipUntil(tok::r_brace, true);
453        return 0;
454      }
455
456      return ParseCXXInlineMethodDef(AS, DeclaratorInfo);
457    }
458  }
459
460  // member-declarator-list:
461  //   member-declarator
462  //   member-declarator-list ',' member-declarator
463
464  DeclTy *LastDeclInGroup = 0;
465  ExprTy *BitfieldSize = 0;
466  ExprTy *Init = 0;
467
468  while (1) {
469
470    // member-declarator:
471    //   declarator pure-specifier[opt]
472    //   declarator constant-initializer[opt]
473    //   identifier[opt] ':' constant-expression
474
475    if (Tok.is(tok::colon)) {
476      ConsumeToken();
477      ExprResult Res = ParseConstantExpression();
478      if (Res.isInvalid)
479        SkipUntil(tok::comma, true, true);
480      else
481        BitfieldSize = Res.Val;
482    }
483
484    // pure-specifier:
485    //   '= 0'
486    //
487    // constant-initializer:
488    //   '=' constant-expression
489
490    if (Tok.is(tok::equal)) {
491      ConsumeToken();
492      ExprResult Res = ParseInitializer();
493      if (Res.isInvalid)
494        SkipUntil(tok::comma, true, true);
495      else
496        Init = Res.Val;
497    }
498
499    // If attributes exist after the declarator, parse them.
500    if (Tok.is(tok::kw___attribute))
501      DeclaratorInfo.AddAttributes(ParseAttributes());
502
503    // NOTE: If Sema is the Action module and declarator is an instance field,
504    // this call will *not* return the created decl; LastDeclInGroup will be
505    // returned instead.
506    // See Sema::ActOnCXXMemberDeclarator for details.
507    LastDeclInGroup = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
508                                                       DeclaratorInfo,
509                                                       BitfieldSize, Init,
510                                                       LastDeclInGroup);
511
512    // If we don't have a comma, it is either the end of the list (a ';')
513    // or an error, bail out.
514    if (Tok.isNot(tok::comma))
515      break;
516
517    // Consume the comma.
518    ConsumeToken();
519
520    // Parse the next declarator.
521    DeclaratorInfo.clear();
522    BitfieldSize = Init = 0;
523
524    // Attributes are only allowed on the second declarator.
525    if (Tok.is(tok::kw___attribute))
526      DeclaratorInfo.AddAttributes(ParseAttributes());
527
528    if (Tok.isNot(tok::colon))
529      ParseDeclarator(DeclaratorInfo);
530  }
531
532  if (Tok.is(tok::semi)) {
533    ConsumeToken();
534    // Reverse the chain list.
535    return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
536  }
537
538  Diag(Tok, diag::err_expected_semi_decl_list);
539  // Skip to end of block or statement
540  SkipUntil(tok::r_brace, true, true);
541  if (Tok.is(tok::semi))
542    ConsumeToken();
543  return 0;
544}
545
546/// ParseCXXMemberSpecification - Parse the class definition.
547///
548///       member-specification:
549///         member-declaration member-specification[opt]
550///         access-specifier ':' member-specification[opt]
551///
552void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
553                                         unsigned TagType, DeclTy *TagDecl) {
554  assert((TagType == DeclSpec::TST_struct ||
555         TagType == DeclSpec::TST_union  ||
556         TagType == DeclSpec::TST_class) && "Invalid TagType!");
557
558  SourceLocation LBraceLoc = ConsumeBrace();
559
560  if (!CurScope->isCXXClassScope() && // Not about to define a nested class.
561      CurScope->isInCXXInlineMethodScope()) {
562    // We will define a local class of an inline method.
563    // Push a new LexedMethodsForTopClass for its inline methods.
564    PushTopClassStack();
565  }
566
567  // Enter a scope for the class.
568  EnterScope(Scope::CXXClassScope|Scope::DeclScope);
569
570  Actions.ActOnStartCXXClassDef(CurScope, TagDecl, LBraceLoc);
571
572  // C++ 11p3: Members of a class defined with the keyword class are private
573  // by default. Members of a class defined with the keywords struct or union
574  // are public by default.
575  AccessSpecifier CurAS;
576  if (TagType == DeclSpec::TST_class)
577    CurAS = AS_private;
578  else
579    CurAS = AS_public;
580
581  // While we still have something to read, read the member-declarations.
582  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
583    // Each iteration of this loop reads one member-declaration.
584
585    // Check for extraneous top-level semicolon.
586    if (Tok.is(tok::semi)) {
587      Diag(Tok, diag::ext_extra_struct_semi);
588      ConsumeToken();
589      continue;
590    }
591
592    AccessSpecifier AS = getAccessSpecifierIfPresent();
593    if (AS != AS_none) {
594      // Current token is a C++ access specifier.
595      CurAS = AS;
596      ConsumeToken();
597      ExpectAndConsume(tok::colon, diag::err_expected_colon);
598      continue;
599    }
600
601    // Parse all the comma separated declarators.
602    ParseCXXClassMemberDeclaration(CurAS);
603  }
604
605  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
606
607  AttributeList *AttrList = 0;
608  // If attributes exist after class contents, parse them.
609  if (Tok.is(tok::kw___attribute))
610    AttrList = ParseAttributes(); // FIXME: where should I put them?
611
612  Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
613                                            LBraceLoc, RBraceLoc);
614
615  // C++ 9.2p2: Within the class member-specification, the class is regarded as
616  // complete within function bodies, default arguments,
617  // exception-specifications, and constructor ctor-initializers (including
618  // such things in nested classes).
619  //
620  // FIXME: Only function bodies are parsed correctly, fix the rest.
621  if (!CurScope->getParent()->isCXXClassScope()) {
622    // We are not inside a nested class. This class and its nested classes
623    // are complete and we can parse the lexed inline method definitions.
624    ParseLexedMethodDefs();
625
626    // For a local class of inline method, pop the LexedMethodsForTopClass that
627    // was previously pushed.
628
629    assert((CurScope->isInCXXInlineMethodScope() ||
630           TopClassStacks.size() == 1) &&
631           "MethodLexers not getting popped properly!");
632    if (CurScope->isInCXXInlineMethodScope())
633      PopTopClassStack();
634  }
635
636  // Leave the class scope.
637  ExitScope();
638
639  Actions.ActOnFinishCXXClassDef(TagDecl);
640}
641