Fixing op description white space during doc emission.
Strip additional whitespacing before and only add required additional indentation back.
PiperOrigin-RevId: 230426127
diff --git a/tools/mlir-tblgen/OpDocGen.cpp b/tools/mlir-tblgen/OpDocGen.cpp
index 870e31e..84dfb9e 100644
--- a/tools/mlir-tblgen/OpDocGen.cpp
+++ b/tools/mlir-tblgen/OpDocGen.cpp
@@ -34,6 +34,47 @@
using mlir::tblgen::Operator;
+// Emit the description by first aligning the text to the left per line (e.g.,
+// removing the minimum indentation across the block) and then indenting by 4.
+// This follows from the expectation that the description in the tablegen file
+// is already formatted in a way the user wanted but has some additional
+// indenting due to being nested in the op definition.
+static void emitDescription(StringRef description, raw_ostream &os) {
+ // Determine the minimum number of spaces in a line.
+ size_t min_indent = -1;
+ StringRef remaining = description;
+ while (!remaining.empty()) {
+ auto split = remaining.split('\n');
+ size_t indent = split.first.find_first_not_of(" \t");
+ if (indent != StringRef::npos)
+ min_indent = std::min(indent, min_indent);
+ remaining = split.second;
+ }
+
+ // Print out the description indented.
+ os << "\n";
+ remaining = description;
+ bool printed = false;
+ while (!remaining.empty()) {
+ auto split = remaining.split('\n');
+ if (split.second.empty()) {
+ // Skip last line with just spaces.
+ if (split.first.ltrim().empty())
+ break;
+ }
+ // Print empty new line without spaces if line only has spaces, unless no
+ // text has been emitted before.
+ if (split.first.ltrim().empty()) {
+ if (printed)
+ os << "\n";
+ } else {
+ os.indent(4) << split.first.substr(min_indent) << "\n";
+ printed = true;
+ }
+ remaining = split.second;
+ }
+}
+
static void emitOpDoc(const RecordKeeper &recordKeeper, raw_ostream &os) {
const auto &defs = recordKeeper.getAllDerivedDefinitions("Op");
os << "<!-- Autogenerated by mlir-tblgen; don't manually edit -->\n";
@@ -51,9 +92,8 @@
if (op.hasSummary())
os << "\n" << op.getSummary();
os << "\n";
- // TODO: Add line level reformatting to ensure spacing is as desired.
if (op.hasDescription())
- os << op.getDescription() << "\n";
+ emitDescription(op.getDescription(), os);
// Emit operands & type of operand. All operands are numbered, some may be
// named too.