1//===- EnumPythonBindingGen.cpp - Generator of Python API for ODS enums ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// EnumPythonBindingGen uses ODS specification of MLIR enum attributes to
10// generate the corresponding Python binding classes.
11//
12//===----------------------------------------------------------------------===//
13#include "OpGenHelpers.h"
14
15#include "mlir/TableGen/AttrOrTypeDef.h"
16#include "mlir/TableGen/Attribute.h"
17#include "mlir/TableGen/Dialect.h"
18#include "mlir/TableGen/EnumInfo.h"
19#include "mlir/TableGen/GenInfo.h"
20#include "llvm/Support/CommandLine.h"
21#include "llvm/Support/FormatVariadic.h"
22#include "llvm/TableGen/Record.h"
23
24using namespace mlir;
25using namespace mlir::tblgen;
26using llvm::formatv;
27using llvm::Record;
28using llvm::RecordKeeper;
29
30// Declared in OpPythonBindingGen.cpp; the two generators share the same
31// -bind-dialect option to allow filtering enum registrations by dialect.
32extern std::string dialectNameStorage;
33
34/// File header and includes.
35constexpr const char *fileHeader = R"Py(
36# Autogenerated by mlir-tblgen; don't manually edit.
37
38from enum import IntEnum, auto, IntFlag
39from ._ods_common import _cext as _ods_cext
40from ..ir import register_attribute_builder
41_ods_ir = _ods_cext.ir
42
43)Py";
44
45/// Makes enum case name Python-compatible, i.e. UPPER_SNAKE_CASE.
46static std::string makePythonEnumCaseName(StringRef name) {
47 if (isPythonReserved(str: name.str()))
48 return (name + "_").str();
49 return name.str();
50}
51
52/// Emits the Python class for the given enum.
53static void emitEnumClass(EnumInfo enumInfo, raw_ostream &os) {
54 os << formatv(Fmt: "class {0}({1}):\n", Vals: enumInfo.getEnumClassName(),
55 Vals: enumInfo.isBitEnum() ? "IntFlag" : "IntEnum");
56 if (!enumInfo.getSummary().empty())
57 os << formatv(Fmt: " \"\"\"{0}\"\"\"\n", Vals: enumInfo.getSummary());
58 os << "\n";
59
60 for (const EnumCase &enumCase : enumInfo.getAllCases()) {
61 os << formatv(Fmt: " {0} = {1}\n",
62 Vals: makePythonEnumCaseName(name: enumCase.getSymbol()),
63 Vals: enumCase.getValue() >= 0 ? std::to_string(val: enumCase.getValue())
64 : "auto()");
65 }
66
67 os << "\n";
68
69 if (enumInfo.isBitEnum()) {
70 os << formatv(Fmt: " def __iter__(self):\n"
71 " return iter([case for case in type(self) if "
72 "(self & case) is case and self is not case])\n");
73 os << formatv(Fmt: " def __len__(self):\n"
74 " return bin(self).count(\"1\")\n");
75 os << "\n";
76 }
77
78 os << formatv(Fmt: " def __str__(self):\n");
79 if (enumInfo.isBitEnum())
80 os << formatv(Fmt: " if len(self) > 1:\n"
81 " return \"{0}\".join(map(str, self))\n",
82 Vals: enumInfo.getBitEnumSeparator());
83 for (const EnumCase &enumCase : enumInfo.getAllCases()) {
84 os << formatv(Fmt: " if self is {0}.{1}:\n", Vals: enumInfo.getEnumClassName(),
85 Vals: makePythonEnumCaseName(name: enumCase.getSymbol()));
86 os << formatv(Fmt: " return \"{0}\"\n", Vals: enumCase.getStr());
87 }
88 os << formatv(Fmt: " raise ValueError(\"Unknown {0} enum entry.\")\n\n\n",
89 Vals: enumInfo.getEnumClassName());
90 os << "\n";
91}
92
93/// Emits an attribute builder for the given enum attribute to support automatic
94/// conversion between enum values and attributes in Python. Returns
95/// `false` on success, `true` on failure.
96static bool emitAttributeBuilder(const EnumInfo &enumInfo, raw_ostream &os) {
97 std::optional<Attribute> enumAttrInfo = enumInfo.asEnumAttr();
98 if (!enumAttrInfo)
99 return false;
100
101 int64_t bitwidth = enumInfo.getBitwidth();
102 // These builders may be emitted by multiple dialect enum_gen files when
103 // dialects share enum definitions via .td includes. Use allow_existing=True
104 // so that the first loaded dialect registers the builder and subsequent
105 // loads silently skip (first-registration wins).
106 os << formatv(Fmt: "@register_attribute_builder(\"{0}\", allow_existing=True)\n",
107 Vals: enumAttrInfo->getAttrDefName());
108 os << formatv(Fmt: "def _{0}(x, context):\n",
109 Vals: enumAttrInfo->getAttrDefName().lower());
110 os << formatv(Fmt: " return "
111 "_ods_ir.IntegerAttr.get(_ods_ir.IntegerType.get_signless({0}, "
112 "context=context), int(x))\n\n",
113 Vals&: bitwidth);
114 return false;
115}
116
117/// Emits an attribute builder for the given dialect enum attribute to support
118/// automatic conversion between enum values and attributes in Python. Returns
119/// `false` on success, `true` on failure.
120static bool emitDialectEnumAttributeBuilder(StringRef dialect,
121 StringRef attrDefName,
122 StringRef formatString,
123 raw_ostream &os) {
124 os << formatv(Fmt: "@register_attribute_builder(\"{0}.{1}\")\n", Vals&: dialect,
125 Vals&: attrDefName);
126 os << formatv(Fmt: "def _{0}(x, context):\n", Vals: attrDefName.lower());
127 os << formatv(Fmt: " return "
128 "_ods_ir.Attribute.parse(f'{0}', context=context)\n\n",
129 Vals&: formatString);
130 return false;
131}
132
133/// Emits Python bindings for all enums in the record keeper. Returns
134/// `false` on success, `true` on failure.
135static bool emitPythonEnums(const RecordKeeper &records, raw_ostream &os) {
136 os << fileHeader;
137 for (const Record *it :
138 records.getAllDerivedDefinitionsIfDefined(ClassName: "EnumInfo")) {
139 EnumInfo enumInfo(*it);
140 emitEnumClass(enumInfo, os);
141 emitAttributeBuilder(enumInfo, os);
142 }
143 for (const Record *it :
144 records.getAllDerivedDefinitionsIfDefined(ClassName: "EnumAttr")) {
145 AttrOrTypeDef attr(&*it);
146 StringRef dialect = attr.getDialect().getName();
147 // When -bind-dialect is specified, only emit builders for EnumAttr records
148 // belonging to that dialect. This prevents duplicate registrations when
149 // multiple dialects include the same .td files.
150 if (!dialectNameStorage.empty() && dialect != dialectNameStorage)
151 continue;
152 if (!attr.getMnemonic()) {
153 llvm::errs() << "enum case " << attr
154 << " needs mnemonic for python enum bindings generation";
155 return true;
156 }
157 StringRef mnemonic = attr.getMnemonic().value();
158 std::optional<StringRef> assemblyFormat = attr.getAssemblyFormat();
159 if (assemblyFormat == "`<` $value `>`") {
160 emitDialectEnumAttributeBuilder(
161 dialect, attrDefName: attr.getName(),
162 formatString: formatv(Fmt: "#{0}.{1}<{{str(x)}>", Vals&: dialect, Vals&: mnemonic).str(), os);
163 } else if (assemblyFormat == "$value") {
164 emitDialectEnumAttributeBuilder(
165 dialect, attrDefName: attr.getName(),
166 formatString: formatv(Fmt: "#{0}<{1} {{str(x)}>", Vals&: dialect, Vals&: mnemonic).str(), os);
167 } else {
168 llvm::errs()
169 << "unsupported assembly format for python enum bindings generation";
170 return true;
171 }
172 }
173
174 return false;
175}
176
177// Registers the enum utility generator to mlir-tblgen.
178static mlir::GenRegistration
179 genPythonEnumBindings("gen-python-enum-bindings",
180 "Generate Python bindings for enum attributes",
181 &emitPythonEnums);
182