MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / emit_class

Method emit_class

imperative/tablegen/targets/python_c_extension.cpp:513–575  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

511}
512
513void OpDefEmitter::emit_class() {
514 auto&& className = op.getCppClassName();
515 std::string method_defs;
516 std::vector<std::string> body;
517
518 llvm::for_each(op.getMgbAttributes(), [&](auto&& attr) {
519 body.push_back(
520 formatv(R"(
521 {{"{0}", serialization<decltype(opdef.{0})>::dump(opdef.{0})})",
522 attr.name));
523 });
524 method_defs +=
525 formatv(R"(
526 static PyObject* getstate(PyObject* self, PyObject*) {{
527 auto& opdef = reinterpret_cast<PyOp({0})*>(self)->inst();
528 static_cast<void>(opdef);
529 std::unordered_map<std::string, py::object> state {{
530 {1}
531 };
532 return py::cast(state).release().ptr();
533 })",
534 className, llvm::join(body, ","));
535
536 body.clear();
537 llvm::for_each(op.getMgbAttributes(), [&](auto&& attr) {
538 body.push_back(
539 formatv(R"(
540 {{
541 auto&& iter = state.find("{0}");
542 if (iter != state.end()) {
543 opdef.{0} = serialization<decltype(opdef.{0})>::load(iter->second);
544 }
545 })",
546 attr.name));
547 });
548
549 method_defs +=
550 formatv(R"(
551 static PyObject* setstate(PyObject* self, PyObject* args) {{
552 PyObject* dict = PyTuple_GetItem(args, 0);
553 if (!dict) return NULL;
554 auto state = py::cast<std::unordered_map<std::string, py::object>>(dict);
555 auto& opdef = reinterpret_cast<PyOp({0})*>(self)->inst();
556 static_cast<void>(opdef);
557 {1}
558 Py_RETURN_NONE;
559 })",
560 className, llvm::join(body, "\n"));
561
562 os << tgfmt(
563 R"(
564PyOpDefBegin($_self) // {
565 static PyGetSetDef py_getsetters[];
566 static PyMethodDef tp_methods[];
567 $0
568 static int py_init(PyObject *self, PyObject *args, PyObject *kwds);
569 static PyObject* py_init_proxy(PyObject *self, PyObject *args, PyObject *kwds);
570 static PyMethodDef py_init_methoddef;

Callers

nothing calls this directly

Calls 3

getMgbAttributesMethod · 0.80
push_backMethod · 0.45
clearMethod · 0.45

Tested by

no test coverage detected