#include <torch/csrc/dynamo/framelocals_mapping.h>
#include <c10/util/irange.h>
#include <torch/csrc/dynamo/cpython_includes.h>
#include <torch/csrc/dynamo/debug_macros.h>
#define Py_BUILD_CORE
#include <internal/pycore_code.h>
#undef Py_BUILD_CORE
FrameLocalsMapping::FrameLocalsMapping(FrameLocalsFrameType* frame)
: _code_obj(py::cast<py::object>((PyObject*)F_CODE(frame))) {
PyCodeObject* co = F_CODE(frame);
_framelocals.resize(co->co_nlocalsplus, nullptr);
#if IS_PYTHON_3_16_PLUS
TORCH_CHECK(false, "Python 3.16+");
#elif IS_PYTHON_3_14_PLUS
if (!frame->stackpointer) {
return;
}
#else
if (!frame->stacktop) {
return;
}
#endif
auto update_framelocals = [&](int i, PyObject* value) {
_PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
if (kind & CO_FAST_FREE && !(co->co_flags & CO_OPTIMIZED)) {
return;
}
#if IS_PYTHON_3_12_PLUS
if (kind & CO_FAST_HIDDEN) {
return;
}
#endif
if (kind & CO_FAST_FREE) {
CHECK(value != nullptr && PyCell_Check(value));
value = PyCell_GET(value);
}
DEBUG_CHECK(0 <= i && i < _framelocals.size());
_framelocals[i] = value;
};
auto offset = co->co_nlocalsplus - co->co_nfreevars;
#if IS_PYTHON_3_16_PLUS
TORCH_CHECK(false, "Python 3.16+");
#elif IS_PYTHON_3_14_PLUS
for (const auto i : c10::irange(offset)) {
update_framelocals(
i, THP_PyStackRef_AsPyObjectBorrow(&frame->localsplus[i]));
}
#else
for (const auto i : c10::irange(offset)) {
update_framelocals(i, frame->localsplus[i]);
}
#endif
#if IS_PYTHON_3_16_PLUS
PyObject* closure;
TORCH_CHECK(false, "Python 3.16+");
#else
PyObject* closure = FUNC(frame)->func_closure;
#endif
for (const auto i : c10::irange(co->co_nfreevars)) {
update_framelocals(offset + i, PyTuple_GET_ITEM(closure, i));
}
}
void FrameLocalsMapping::_realize_dict() {
_dict = py::dict();
py::tuple framelocals_names = code_framelocals_names(_code_obj);
auto nlocalsplus = ((PyCodeObject*)_code_obj.ptr())->co_nlocalsplus;
DEBUG_CHECK(nlocalsplus == _framelocals.size());
for (const auto i : c10::irange(nlocalsplus)) {
if (_framelocals[i]) {
_dict[framelocals_names[i]] = _framelocals[i];
}
}
}
py::tuple code_framelocals_names(py::handle code) {
CHECK(PyCode_Check(code.ptr()));
return py::cast<py::tuple>(((PyCodeObject*)code.ptr())->co_localsplusnames);
}
PyObject* FrameLocalsMapping::get(int idx) {
DEBUG_CHECK(0 <= idx && idx < _framelocals.size());
return _framelocals[idx].ptr();
}
PyDictObject* framelocals_mapping_to_dict(FrameLocalsMapping* map) {
return map->to_dict();
}