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

Method emit_py_init

imperative/tablegen/targets/python_c_extension.cpp:577–643  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

575}
576
577void OpDefEmitter::emit_py_init() {
578 std::string initBody;
579 if (!op.getMgbAttributes().empty()) {
580 initBody += "static const char* kwlist[] = {";
581
582 std::vector<llvm::StringRef> attr_name_list;
583 llvm::for_each(op.getMgbAttributes(), [&](auto&& attr) {
584 attr_name_list.push_back(attr.name);
585 });
586 attr_name_list.push_back("scope");
587
588 llvm::for_each(attr_name_list, [&](auto&& attr) {
589 initBody += formatv("\"{0}\", ", attr);
590 });
591 initBody += "NULL};\n";
592 initBody += " PyObject ";
593 auto initializer = [&](auto&& attr) -> std::string {
594 return formatv("*{0} = NULL", attr);
595 };
596 initBody +=
597 llvm::join(llvm::map_range(attr_name_list, initializer), ", ") + ";\n";
598 initBody += " if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|";
599 // an extra slot created for name
600 initBody += std::string(attr_name_list.size(), 'O');
601 initBody += "\", const_cast<char**>(kwlist)";
602 llvm::for_each(attr_name_list, [&](auto&& attr) {
603 initBody += formatv(", &{0}", attr);
604 });
605 initBody += "))\n";
606 initBody += " return -1;\n";
607
608 llvm::for_each(op.getMgbAttributes(), [&](auto&& attr) {
609 initBody +=
610 tgfmt(R"(
611 if ($0) {
612 try {
613 // TODO: remove this guard which is used for pybind11 implicit conversion
614 py::detail::loader_life_support guard{};
615 reinterpret_cast<PyOp($_self)*>(self)->inst().$0 =
616 py::cast<decltype($_self::$0)>(py::handle($0));
617 } CATCH_ALL(-1)
618 }
619)",
620 &ctx, attr.name);
621 });
622
623 initBody +=
624 tgfmt(R"(
625 if (scope) {
626 try {
627 reinterpret_cast<PyOp(OpDef)*>(self)->op
628 ->set_scope(py::cast<std::string>(py::handle(scope)));
629 } CATCH_ALL(-1)
630 }
631)",
632 &ctx);
633 }
634 initBody += "\n return 0;";

Callers

nothing calls this directly

Calls 4

getMgbAttributesMethod · 0.80
emptyMethod · 0.45
push_backMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected