]> granicus.if.org Git - clang/commitdiff
Parsing and AST support for using declarations, from John Thompson!
authorDouglas Gregor <dgregor@apple.com>
Sat, 20 Jun 2009 00:51:54 +0000 (00:51 +0000)
committerDouglas Gregor <dgregor@apple.com>
Sat, 20 Jun 2009 00:51:54 +0000 (00:51 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@73812 91177308-0d34-0410-b5e6-96231b3b80d8

18 files changed:
include/clang/AST/DeclBase.h
include/clang/AST/DeclCXX.h
include/clang/AST/DeclNodes.def
include/clang/Basic/DiagnosticParseKinds.td
include/clang/Basic/DiagnosticSemaKinds.td
include/clang/Parse/Action.h
lib/AST/DeclBase.cpp
lib/AST/DeclCXX.cpp
lib/CodeGen/CodeGenModule.cpp
lib/Parse/MinimalAction.cpp
lib/Parse/ParseDeclCXX.cpp
lib/Sema/Sema.h
lib/Sema/SemaDecl.cpp
lib/Sema/SemaDeclCXX.cpp
lib/Sema/SemaLookup.cpp
test/Parser/cxx-using-declaration.cpp [new file with mode: 0644]
test/Parser/cxx-using-directive.cpp
test/SemaCXX/using-directive.cpp

index e2ca1a3298b049e29ea1c7db19058091bf00f9fc..a2ee8952568496ece5c2e0fad3b4f95ef6c2470e 100644 (file)
@@ -159,10 +159,12 @@ private:
   /// \brief Whether this declaration was "used", meaning that a definition is
   /// required.
   bool Used : 1;
-  
+
+protected:
   /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
   unsigned IdentifierNamespace : 8;
   
+private:
 #ifndef NDEBUG
   void CheckAccessDeclContext() const;
 #else
index 1216eb09ee8440cd2a5a954f485fb5f695d2804d..9ca1823f38229d978d75e64597cdbd9c3db6c106 100644 (file)
@@ -1049,6 +1049,61 @@ public:
   }
   static bool classof(const NamespaceAliasDecl *D) { return true; }
 };
+
+/// UsingDecl - Represents a C++ using-declaration. For example:
+///    using someNameSpace::someIdentifier;
+class UsingDecl : public NamedDecl {
+
+  /// \brief The source range that covers the nested-name-specifier
+  /// preceding the declaration name.
+  SourceRange NestedNameRange;
+  /// \brief The source location of the target declaration name.
+  SourceLocation TargetNameLocation;
+  /// \brief The source location of the "using" location itself.
+  SourceLocation UsingLocation;
+  /// \brief Target declaration.
+  NamedDecl* TargetDecl;
+  /// \brief Target declaration.
+  NestedNameSpecifier* TargetNestedNameDecl;
+
+  // Had 'typename' keyword.
+  bool IsTypeName;
+
+  UsingDecl(DeclContext *DC, SourceLocation L, SourceRange NNR,
+            SourceLocation TargetNL, SourceLocation UL, NamedDecl* Target,
+            NestedNameSpecifier* TargetNNS, bool IsTypeNameArg)
+    : NamedDecl(Decl::Using, DC, L, Target->getDeclName()),
+      NestedNameRange(NNR), TargetNameLocation(TargetNL),
+      UsingLocation(UL), TargetDecl(Target),
+      TargetNestedNameDecl(TargetNNS), IsTypeName(IsTypeNameArg) { 
+    this->IdentifierNamespace = TargetDecl->getIdentifierNamespace();
+  }
+
+public:
+  /// \brief Returns the source range that covers the nested-name-specifier
+  /// preceding the namespace name.
+  SourceRange getNestedNameRange() { return(NestedNameRange); }
+  /// \brief Returns the source location of the target declaration name.
+  SourceLocation getTargetNameLocation() { return(TargetNameLocation); }
+  /// \brief Returns the source location of the "using" location itself.
+  SourceLocation getUsingLocation() { return(UsingLocation); }
+  /// \brief getTargetDecl - Returns target specified by using-decl.
+  NamedDecl *getTargetDecl() { return(TargetDecl); }
+  /// \brief Get target nested name declaration.
+  NestedNameSpecifier* getTargetNestedNameDecl() { return(TargetNestedNameDecl); }
+  /// isTypeName - Return true if using decl had 'typename'.
+  bool isTypeName() const { return(IsTypeName); }
+
+  static UsingDecl *Create(ASTContext &C, DeclContext *DC,
+      SourceLocation L, SourceRange NNR, SourceLocation TargetNL,
+      SourceLocation UL, NamedDecl* Target,
+      NestedNameSpecifier* TargetNNS, bool IsTypeNameArg);
+
+  static bool classof(const Decl *D) {
+    return D->getKind() == Decl::Using;
+  }
+  static bool classof(const UsingDecl *D) { return true; }
+};
   
 /// StaticAssertDecl - Represents a C++0x static_assert declaration.
 class StaticAssertDecl : public Decl {
index d1b921a4cb65508ff1201ace46e7f55985cc52ad..1e4440357b655c11338d3e44f0bbc2b5c9889cae 100644 (file)
@@ -108,6 +108,7 @@ ABSTRACT_DECL(Named,  Decl)
     DECL(FunctionTemplate, TemplateDecl)
     DECL(ClassTemplate, TemplateDecl)
     DECL(TemplateTemplateParm, TemplateDecl)
+  DECL(Using, NamedDecl)
   DECL(ObjCMethod, NamedDecl)
   DECL(ObjCContainer, NamedDecl)
     DECL(ObjCCategory, ObjCContainerDecl)
index ccb59eb51c22c040b7336af41c012ce9ea60433d..d65a97eb7067b661efd3fc42e410d3dc348bb2a6 100644 (file)
@@ -154,6 +154,10 @@ def err_unknown_typename : Error<
   "unknown type name %0">;
 def err_use_of_tag_name_without_tag : Error<
   "use of tagged type %0 without '%1' tag">;
+def err_expected_ident_in_using : Error<
+  "expected an identifier in using directive">;
+def err_unexpected_template_spec_in_using : Error<
+  "use of template specialization in using directive not allowed">;
 
 
 /// Objective-C parser diagnostics
@@ -214,6 +218,8 @@ def ext_ellipsis_exception_spec : Extension<
   "exception specification of '...' is a Microsoft extension">;
 def err_expected_catch : Error<"expected catch">;
 def err_expected_lbrace_or_comma : Error<"expected '{' or ','">;
+def err_using_namespace_in_class : Error<
+  "'using namespace' in class not allowed">;
 
 // C++ derived classes
 def err_dup_virtual : Error<"duplicate 'virtual' in base specifier">;
@@ -289,5 +295,5 @@ def warn_pragma_unused_expected_var : Warning<
   "expected '#pragma unused' argument to be a variable name">;
 def warn_pragma_unused_expected_punc : Warning<
   "expected ')' or ',' in '#pragma unused'">;
-  
+
 } // end of Parser diagnostics
index 855b7b9d29dd67938626a26b5580790895079f78..6bd925797ad63cfce41066f7465fbcfe393dd407 100644 (file)
@@ -92,6 +92,10 @@ def warn_use_out_of_scope_declaration : Warning<
   "use of out-of-scope declaration of %0">;
 def err_inline_non_function : Error<
   "'inline' can only appear on functions">;
+def err_using_requires_qualname : Error<
+  "using declaration requires a qualified name">;
+def err_using_typename_non_type : Error<
+  "'typename' keyword used on a non-type">;
 
 def err_invalid_thread : Error<
   "'__thread' is only allowed on variable declarations">;
index 47583993bc26fad8052b5151f17db36da2bb5376..5b57521f67514c686b6728279a1ddba37e1f8836 100644 (file)
@@ -932,6 +932,15 @@ public:
                                            IdentifierInfo *Ident) {
     return DeclPtrTy();
   }
+
+  /// ActOnUsingDirective - This is called when using-directive is parsed.
+  virtual DeclPtrTy ActOnUsingDeclaration(Scope *CurScope,
+                                        SourceLocation UsingLoc,
+                                        const CXXScopeSpec &SS,
+                                        SourceLocation IdentLoc,
+                                        IdentifierInfo *TargetName,
+                                        AttributeList *AttrList,
+                                        bool IsTypeName);
                                          
   /// ActOnParamDefaultArgument - Parse default argument for function parameter
   virtual void ActOnParamDefaultArgument(DeclPtrTy param,
index b83a503dbb2fb9f906a585abf71a9b01be7d7b2d..02e71d7a8681efe20a5219e6c744e3678b7899f0 100644 (file)
@@ -164,6 +164,7 @@ unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
     case ParmVar:
     case OriginalParmVar:
     case NonTypeTemplateParm:
+    case Using:
     case ObjCMethod:
     case ObjCContainer:
     case ObjCCategory:
index 2fa5ed7919df2a4c3550ade9cf7587ca531ae5dc..7a930d78c12365f333dd17b9867b3e2070b11847 100644 (file)
@@ -443,6 +443,14 @@ NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
                                     Qualifier, IdentLoc, Namespace);
 }
 
+UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC,
+      SourceLocation L, SourceRange NNR, SourceLocation TargetNL,
+      SourceLocation UL, NamedDecl* Target,
+      NestedNameSpecifier* TargetNNS, bool IsTypeNameArg) {
+  return new (C) UsingDecl(DC, L, NNR, TargetNL, UL, Target,
+      TargetNNS, IsTypeNameArg);
+}
+
 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
                                            SourceLocation L, Expr *AssertExpr,
                                            StringLiteral *Message) {
index f8dfbfb532f57deb20c9bf0ce69a2cd9b32032e5..f926c05a998300ef3dce45b44858611d6e1929bb 100644 (file)
@@ -1481,6 +1481,9 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) {
   case Decl::Namespace:
     EmitNamespace(cast<NamespaceDecl>(D));
     break;
+    // No code generation needed.
+  case Decl::Using:
+    break;
   case Decl::CXXConstructor:
     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
     break;
index b018e36519f3cb2818c5b3d26ef2349efc84bc6c..9ded366b29f91b5c23719d8338725395194fc5c1 100644 (file)
@@ -42,6 +42,22 @@ Action::DeclPtrTy Action::ActOnUsingDirective(Scope *CurScope,
   return DeclPtrTy();
 }
 
+// Defined out-of-line here because of dependecy on AttributeList
+Action::DeclPtrTy Action::ActOnUsingDeclaration(Scope *CurScope,
+                                              SourceLocation UsingLoc,
+                                              const CXXScopeSpec &SS,
+                                              SourceLocation IdentLoc,
+                                              IdentifierInfo *TargetName,
+                                              AttributeList *AttrList,
+                                              bool IsTypeName) {
+  
+  // FIXME: Parser seems to assume that Action::ActOn* takes ownership over
+  // passed AttributeList, however other actions don't free it, is it
+  // temporary state or bug?
+  delete AttrList;
+  return DeclPtrTy();
+}
+
 
 void PrettyStackTraceActionsDecl::print(llvm::raw_ostream &OS) const {
   if (Loc.isValid()) {
index 1427814c9342561f12c9344427dcc83524c62272..44f231a667862fade2e64f48f878e4361c6b5e54 100644 (file)
@@ -253,15 +253,62 @@ Parser::DeclPtrTy Parser::ParseUsingDirective(unsigned Context,
 ///
 ///     using-declaration: [C++ 7.3.p3: namespace.udecl]
 ///       'using' 'typename'[opt] ::[opt] nested-name-specifier
-///               unqualified-id [TODO]
-///       'using' :: unqualified-id [TODO]
+///               unqualified-id
+///       'using' :: unqualified-id
 ///
 Parser::DeclPtrTy Parser::ParseUsingDeclaration(unsigned Context,
                                                 SourceLocation UsingLoc,
                                                 SourceLocation &DeclEnd) {
-  assert(false && "Not implemented");
-  // FIXME: Implement parsing.
-  return DeclPtrTy();
+  CXXScopeSpec SS;
+  bool IsTypeName;
+
+  // Ignore optional 'typename'.
+  if (Tok.is(tok::kw_typename)) {
+    ConsumeToken();
+    IsTypeName = true;
+  }
+  else
+    IsTypeName = false;
+
+  // Parse nested-name-specifier.
+  ParseOptionalCXXScopeSpecifier(SS);
+
+  AttributeList *AttrList = 0;
+  IdentifierInfo *TargetName = 0;
+  SourceLocation IdentLoc = SourceLocation();
+
+  // Check nested-name specifier.
+  if (SS.isInvalid()) {
+    SkipUntil(tok::semi);
+    return DeclPtrTy();
+  }
+  if (Tok.is(tok::annot_template_id)) {
+    Diag(Tok, diag::err_unexpected_template_spec_in_using);
+    SkipUntil(tok::semi);
+    return DeclPtrTy();
+  }
+  if (Tok.isNot(tok::identifier)) {
+    Diag(Tok, diag::err_expected_ident_in_using);
+    // If there was invalid identifier, skip to end of decl, and eat ';'.
+    SkipUntil(tok::semi);
+    return DeclPtrTy();
+  }
+  
+  // Parse identifier.
+  TargetName = Tok.getIdentifierInfo();
+  IdentLoc = ConsumeToken();
+  
+  // Parse (optional) attributes (most likely GNU strong-using extension).
+  if (Tok.is(tok::kw___attribute))
+    AttrList = ParseAttributes();
+  
+  // Eat ';'.
+  DeclEnd = Tok.getLocation();
+  ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
+                   AttrList ? "attributes list" : "namespace name", tok::semi);
+
+  return Actions.ActOnUsingDeclaration(CurScope, UsingLoc, SS,
+                                      IdentLoc, TargetName, AttrList, IsTypeName);
 }
 
 /// ParseStaticAssertDeclaration - Parse C++0x static_assert-declaratoion.
@@ -790,7 +837,23 @@ void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) {
     ConsumeToken();
     return ParseCXXClassMemberDeclaration(AS);
   }
-  
+
+  if (Tok.is(tok::kw_using)) {
+    // Eat 'using'.
+    SourceLocation UsingLoc = ConsumeToken();
+
+    if (Tok.is(tok::kw_namespace)) {
+      Diag(UsingLoc, diag::err_using_namespace_in_class);
+      SkipUntil(tok::semi, true, true);
+    }
+    else {
+      SourceLocation DeclEnd;
+      // Otherwise, it must be using-declaration.
+      ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd);
+    }
+    return;
+  }
+
   SourceLocation DSStart = Tok.getLocation();
   // decl-specifier-seq:
   // Parse the common declaration-specifiers piece.
index 230bcffa722bdc8060aea6c4843a68a02cc2dac7..560f952bffa56458d75aa49be1132f02f6a8896f 100644 (file)
@@ -1547,6 +1547,14 @@ public:
                                            const CXXScopeSpec &SS,
                                            SourceLocation IdentLoc,
                                            IdentifierInfo *Ident);
+
+  virtual DeclPtrTy ActOnUsingDeclaration(Scope *CurScope,
+                                        SourceLocation UsingLoc,
+                                        const CXXScopeSpec &SS,
+                                        SourceLocation IdentLoc,
+                                        IdentifierInfo *TargetName,
+                                        AttributeList *AttrList,
+                                        bool IsTypeName);
   
   /// AddCXXDirectInitializerToDecl - This action is called immediately after 
   /// ActOnDeclarator, when a C++ direct initializer is present.
index 2dd02af7b91cb93cffd064700d648c485dbd89c9..06fd1a17362aa96c45077197a85c16a0590cce72 100644 (file)
@@ -2284,7 +2284,7 @@ Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
       Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
         << D.getCXXScopeSpec().getRange();
       NewFD->setInvalidDecl();
-    } else if (!Redeclaration) {
+    } else if (!Redeclaration && (!PrevDecl || !isa<UsingDecl>(PrevDecl))) {
       // The user tried to provide an out-of-line definition for a
       // function that is a member of a class or namespace, but there
       // was no such member function declared (C++ [class.mfct]p2, 
@@ -2455,7 +2455,8 @@ void Sema::CheckFunctionDeclaration(FunctionDecl *NewFD, NamedDecl *&PrevDecl,
 
     if (PrevDecl && 
         (!AllowOverloadingOfFunction(PrevDecl, Context) || 
-         !IsOverload(NewFD, PrevDecl, MatchedDecl))) {
+         !IsOverload(NewFD, PrevDecl, MatchedDecl)) &&
+        !isa<UsingDecl>(PrevDecl)) {
       Redeclaration = true;
       Decl *OldDecl = PrevDecl;
 
index 8c547cd1ccf6e65f361d48770ed70e5bdad796ff..7524cbf500936401f09158d183a401b57a65f047 100644 (file)
@@ -1748,6 +1748,43 @@ void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
     S->PushUsingDirective(DeclPtrTy::make(UDir));
 }
 
+
+Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
+                                          SourceLocation UsingLoc,
+                                          const CXXScopeSpec &SS,
+                                          SourceLocation IdentLoc,
+                                          IdentifierInfo *TargetName,
+                                          AttributeList *AttrList,
+                                          bool IsTypeName) {
+  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
+  assert(TargetName && "Invalid TargetName.");
+  assert(IdentLoc.isValid() && "Invalid TargetName location.");
+  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
+
+  UsingDecl *UsingAlias = 0;
+
+  // Lookup target name.
+  LookupResult R = LookupParsedName(S, &SS, TargetName,
+                                    LookupOrdinaryName, false);
+
+  if (NamedDecl *NS = R) {
+    if (IsTypeName && !isa<TypeDecl>(NS)) {
+      Diag(IdentLoc, diag::err_using_typename_non_type);
+    }
+    UsingAlias = UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
+        NS->getLocation(), UsingLoc, NS,
+        static_cast<NestedNameSpecifier *>(SS.getScopeRep()),
+        IsTypeName);
+    PushOnScopeChains(UsingAlias, S);
+  } else {
+    Diag(IdentLoc, diag::err_using_requires_qualname) << SS.getRange();
+  }
+
+  // FIXME: We ignore attributes for now.
+  delete AttrList;
+  return DeclPtrTy::make(UsingAlias);
+}
+
 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
 /// is a namespace alias, returns the namespace it points to.
 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
index 52de4e6f4c0b1255a63587a2c9d46325a7b5e50d..37e1df3a197d9936419aa347a01a13b6d7902bd5 100644 (file)
@@ -1151,8 +1151,10 @@ Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
                                Name, NameKind, RedeclarationOnly);
   }
 
-  return LookupName(S, Name, NameKind, RedeclarationOnly, 
-                    AllowBuiltinCreation, Loc);
+  LookupResult result(LookupName(S, Name, NameKind, RedeclarationOnly, 
+                    AllowBuiltinCreation, Loc));
+  
+  return(result);
 }
 
 
diff --git a/test/Parser/cxx-using-declaration.cpp b/test/Parser/cxx-using-declaration.cpp
new file mode 100644 (file)
index 0000000..de0e6f1
--- /dev/null
@@ -0,0 +1,45 @@
+// RUN: clang-cc -fsyntax-only -verify %s\r
+\r
+namespace A {\r
+    int VA;\r
+    void FA() {}\r
+    struct SA { int V; };\r
+}\r
+\r
+using A::VA;\r
+using A::FA;\r
+using typename A::SA;\r
+\r
+void main()\r
+{\r
+    VA = 1;\r
+    FA();\r
+    SA x;   //Still needs handling.\r
+}\r
+\r
+struct B {\r
+    void f(char){};\r
+    void g(char){};\r
+};\r
+struct D : B {\r
+    using B::f;\r
+    void f(int);\r
+    void g(int);\r
+};\r
+void D::f(int) { f('c'); } // calls B::f(char)\r
+void D::g(int) { g('c'); } // recursively calls D::g(int)\r
+\r
+namespace E {\r
+    template <typename TYPE> int funcE(TYPE arg) { return(arg); }\r
+}\r
+\r
+using E::funcE<int>; // expected-error{{use of template specialization in using directive not allowed}}\r
+\r
+namespace F {\r
+    struct X;\r
+}\r
+\r
+using F::X;\r
+// Should have some errors here.  Waiting for implementation.\r
+void X(int);\r
+struct X *x;\r
index 676f4e6c5a5e1d6a8962b223b5f1873d7bc86a11..504d026b43919901c58d6a67d25157365776639d 100644 (file)
@@ -13,8 +13,7 @@ namespace D {
   
   class C {
     
-    using namespace B ; // expected-error{{expected member name or ';' after declaration specifiers}}
-    //FIXME: this needs better error message
+    using namespace B ; // expected-error{{not allowed}}
   };
   
   namespace B {}
index 924cf077b63f01f144d1e1b29a672b7360454f24..78ad04293bf47cc506df89e2a12b699263ea6aa1 100644 (file)
@@ -64,7 +64,7 @@ struct K2 k2; // expected-error{{reference to 'K2' is ambiguous}} \
 
 class X { // expected-note{{candidate found by name lookup is 'X'}}
   // FIXME: produce a suitable error message for this
-  using namespace A; // expected-error{{expected member name or}}
+  using namespace A; // expected-error{{not allowed}}
 };
 
 namespace N {