From 7bc09c172af687b04cd2b4cabd60392783a5101d Mon Sep 17 00:00:00 2001 From: Jonas Rembser Date: Fri, 2 Oct 2026 08:31:12 +0000 Subject: [PATCH 1/2] [cpyrt] Skip the using-namespace search for names that don't exist When a namespace lookup fails, meta_getattro() repeats the whole attribute lookup in every namespace pulled in with "using namespace". If the global scope pulls in std, every failed global lookup reruns the full sequence of C++ lookups (class, functions, variables, templates, enums) in std as well, and builds a detailed error message for each of them only to throw it away. Any C++ declaration that this search can find is also found by a single unqualified lookup from within the namespace, which follows the using-directives. Use Cpp::IsVisibleName() for this check and skip the search if it finds nothing. Attributes set on the Python proxies of the using namespaces, directly or transitively, are still found: the search runs if any of them has one. Also reuse the result of GetNamed() instead of repeating the same lookup for enums. For example: import time import cppjit cppjit.cppdef(""" #include namespace Heavy1 { struct S1{}; int handy; void g1(); } namespace Heavy2 { struct S2{}; int handy2; void g2(); } using namespace std; // like ROOT's global scope pulling in std using namespace Heavy1; using namespace Heavy2; """) start = time.perf_counter() for _ in range(10000): try: cppjit.gbl.does_not_exist # failed global lookup, searched in all using-namespaces except AttributeError: pass print(f"10000 failed global lookups: {time.perf_counter() - start:.2f} s") This takes 0.08 s instead of 0.25 s (median of 3 trials, Linux x86_64, Python 3.14, CppInterOp/LLVM 22.1.8). The gap grows with the size of the pulled-in namespaces: with ROOT in the loop, where the global scope also pulls in cling::runtime, the same number of failed lookups takes 0.56 s instead of 4.05 s. Depends on Cpp::IsVisibleName, added to CppInterOp in https://github.com/compiler-research/CppInterOp/pull/1130. --- src/cpyrt/CPPScope.cxx | 117 ++++++++++++++++++++++++-------- src/interop/cppjit_interop.h | 3 + src/interop/interop_wrapper.cxx | 5 ++ 3 files changed, 95 insertions(+), 30 deletions(-) diff --git a/src/cpyrt/CPPScope.cxx b/src/cpyrt/CPPScope.cxx index 9f695789..d53ab263 100644 --- a/src/cpyrt/CPPScope.cxx +++ b/src/cpyrt/CPPScope.cxx @@ -18,6 +18,7 @@ using namespace cppjit; // Standard #include // for for_each +#include #include #include #include @@ -324,6 +325,74 @@ static PyObject* pt_new(PyTypeObject* subtype, PyObject* args, PyObject* kwds) { return (PyObject*)result; } +//---------------------------------------------------------------------------- +static bool IsPlainIdentifier(const std::string& name) { + if (name.empty() || std::isdigit((unsigned char)name[0])) + return false; + for (char c : name) { + if (!std::isalnum((unsigned char)c) && c != '_') + return false; + } + return true; +} + +// Returns weak references to the proxies of the namespaces that the namespace +// \c pyclass pulls in with "using namespace", refreshing the list as needed. +static const std::vector& GetUsingScopes(PyObject* pyclass) { + CPPScope* klass = (CPPScope*)pyclass; + const std::vector& uv = + interop::GetUsingNamespaces(klass->fCppType); + if (!klass->fImp.fUsing || uv.size() != klass->fImp.fUsing->size()) { + if (klass->fImp.fUsing) { + for (auto pyref : *klass->fImp.fUsing) + Py_DECREF(pyref); + klass->fImp.fUsing->clear(); + } else + klass->fImp.fUsing = new std::vector; + + // reload and reset weak refs + for (auto uid : uv) { + std::string uname = interop::GetScopedFinalName(uid); + PyObject* pyuscope = CreateScopeProxy(uname); + if (pyuscope) { + klass->fImp.fUsing->push_back(PyWeakref_NewRef(pyuscope, nullptr)); + // the namespace may not otherwise be held, so tie the lifetimes + PyObject* llname = + PyUnicode_FromString(("__lifeline_" + uname).c_str()); + PyType_Type.tp_setattro(pyclass, llname, pyuscope); + Py_DECREF(llname); + Py_DECREF(pyuscope); + } else { + PyErr_Clear(); + } + } + } + return *klass->fImp.fUsing; +} + +// Checks whether \c pyname is set as a Python attribute on any namespace that +// \c pyclass pulls in with "using namespace", directly or transitively. +static bool HasPythonAttrInUsing(PyObject* pyclass, PyObject* pyname, + std::set& visited) { + for (auto pyref : GetUsingScopes(pyclass)) { + PyObject* pyuscope = cpyrt_GetWeakRef(pyref); + if (!pyuscope) + continue; + bool found = false; + if (visited.insert(pyuscope).second) { + found = _PyType_Lookup((PyTypeObject*)pyuscope, pyname) || + _PyType_Lookup(Py_TYPE(pyuscope), pyname) || + (CPPScope_Check(pyuscope) && + (((CPPScope*)pyuscope)->fFlags & CPPScope::kIsNamespace) && + HasPythonAttrInUsing(pyuscope, pyname, visited)); + } + Py_DECREF(pyuscope); + if (found) + return true; + } + return false; +} + //---------------------------------------------------------------------------- static PyObject* meta_getattro(PyObject* pyclass, PyObject* pyname) { // normal type-based lookup @@ -411,8 +480,9 @@ static PyObject* meta_getattro(PyObject* pyclass, PyObject* pyname) { } } + interop::TCppScope_t lookup_result = nullptr; if (!attr) { - interop::TCppScope_t lookup_result = interop::GetNamed(name, scope); + lookup_result = interop::GetNamed(name, scope); if (interop::IsVariable(lookup_result) || interop::IsEnumConstant(lookup_result)) { attr = (PyObject*)CPPDataMember_New(scope, lookup_result); @@ -450,7 +520,7 @@ static PyObject* meta_getattro(PyObject* pyclass, PyObject* pyname) { // enums types requested as type (rather than the constants) if (!attr) { interop::TCppScope_t enumerator = - interop::GetUnderlyingScope(interop::GetNamed(name, scope)); + interop::GetUnderlyingScope(lookup_result); if (interop::IsEnumScope(enumerator)) { // enum types (incl. named and class enums) attr = (PyObject*)CPPEnum_New(name, enumerator); @@ -481,38 +551,25 @@ static PyObject* meta_getattro(PyObject* pyclass, PyObject* pyname) { } if (!attr && (klass->fFlags & CPPScope::kIsNamespace)) { - // refresh using list as necessary - const std::vector& uv = - interop::GetUsingNamespaces(klass->fCppType); - if (!klass->fImp.fUsing || uv.size() != klass->fImp.fUsing->size()) { - if (klass->fImp.fUsing) { - for (auto pyref : *klass->fImp.fUsing) - Py_DECREF(pyref); - klass->fImp.fUsing->clear(); - } else - klass->fImp.fUsing = new std::vector; - - // reload and reset weak refs - for (auto uid : uv) { - std::string uname = interop::GetScopedFinalName(uid); - PyObject* pyuscope = CreateScopeProxy(uname); - if (pyuscope) { - klass->fImp.fUsing->push_back(PyWeakref_NewRef(pyuscope, nullptr)); - // the namespace may not otherwise be held, so tie the lifetimes - PyObject* llname = - PyUnicode_FromString(("__lifeline_" + uname).c_str()); - PyType_Type.tp_setattro(pyclass, llname, pyuscope); - Py_DECREF(llname); - Py_DECREF(pyuscope); - } else { - PyErr_Clear(); - } - } + const std::vector& using_scopes = GetUsingScopes(pyclass); + + // Searching the using namespaces repeats the full attribute lookup in each + // of them, which is expensive for names that don't exist. Anything C++ it + // can find is also found by a single unqualified lookup from within this + // namespace, which follows the using-directives. If that finds nothing, + // only attributes set on the Python proxies of the using namespaces remain. + bool search_using = !using_scopes.empty(); + if (search_using && IsPlainIdentifier(name) && !interop::IsBuiltin(name) && + !interop::IsVisibleName(name, klass->fCppType)) { + std::set visited{pyclass}; + search_using = HasPythonAttrInUsing(pyclass, pyname, visited); } // try all outstanding using namespaces in turn to find the attribute (will // cache locally later; TODO: doing so may cause pathological cases) - for (auto pyref : *klass->fImp.fUsing) { + for (auto pyref : using_scopes) { + if (!search_using) + break; PyObject* pyuscope = cpyrt_GetWeakRef(pyref); if (pyuscope) { attr = PyObject_GetAttr(pyuscope, pyname); diff --git a/src/interop/cppjit_interop.h b/src/interop/cppjit_interop.h index 883f0a38..8b8694eb 100644 --- a/src/interop/cppjit_interop.h +++ b/src/interop/cppjit_interop.h @@ -101,6 +101,9 @@ RPY_EXPORTED TCppScope_t GetNamed(const std::string& scope_name, TCppScope_t parent_scope = TCppScope_t{}); RPY_EXPORTED +bool IsVisibleName(const std::string& name, + TCppScope_t parent_scope = TCppScope_t{}); +RPY_EXPORTED TCppScope_t GetParentScope(TCppScope_t scope); RPY_EXPORTED TCppScope_t GetScopeFromType(TCppType_t type); diff --git a/src/interop/interop_wrapper.cxx b/src/interop/interop_wrapper.cxx index 735e207c..0b8e4686 100644 --- a/src/interop/interop_wrapper.cxx +++ b/src/interop/interop_wrapper.cxx @@ -710,6 +710,11 @@ interop::TCppScope_t interop::GetNamed(const std::string& name, return Cpp::GetNamed(name, parent_scope); } +bool interop::IsVisibleName(const std::string& name, TCppScope_t parent_scope) { + std::lock_guard Lock(InterOpMutex); + return Cpp::IsVisibleName(name, parent_scope); +} + interop::TCppScope_t interop::GetParentScope(TCppScope_t scope) { std::lock_guard Lock(InterOpMutex); return Cpp::GetParentScope(scope); From cc7edf7dc2f264a683a4ff4dbb1689dbca83f93e Mon Sep 17 00:00:00 2001 From: Aaron Jomy Date: Fri, 2 Oct 2026 14:00:29 +0200 Subject: [PATCH 2/2] test with CppInterOp#1130 --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 79828f6e..c65e398b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,8 +10,8 @@ include(GNUInstallDirs) # This option won't make a lot of sense since we only ship the shared library in site-packages # Perhaps this should permanently be OFF and users can build their own CppInterOp if they want to run the tests? option(CPPJIT_ENABLE_CPPINTEROP_TESTS "enable CppInterOp tests" OFF) -set(CPPINTEROP_GIT_REPOSITORY "https://github.com/compiler-research/CppInterOp.git" CACHE STRING "") -set(CPPINTEROP_GIT_TAG "c8126249dd18363000b89333b34313ca2a83fb82" CACHE STRING "") +set(CPPINTEROP_GIT_REPOSITORY "https://github.com/guitargeek/CppInterOp.git" CACHE STRING "") +set(CPPINTEROP_GIT_TAG "isvisible-name" CACHE STRING "") set(CPPINTEROP_SOURCE_DIR "" CACHE PATH "Override default CppInterOp built by ExternalProject_Add, with a path to local CppInterOp source")