[llvm] [mlir] [NFC][TableGen] Emit nested namespace definitions in NamespaceEmitter (PR #161958)

via llvm-commits llvm-commits at lists.llvm.org
Mon Oct 6 08:20:02 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-mlir

Author: Rahul Joshi (jurahul)

<details>
<summary>Changes</summary>

Change NamespaceEmitter to emit nested namespace using C++17 nested namespace definitions.

---
Full diff: https://github.com/llvm/llvm-project/pull/161958.diff


2 Files Affected:

- (modified) llvm/include/llvm/TableGen/CodeGenHelpers.h (+12-11) 
- (modified) mlir/test/mlir-tblgen/dialect.td (+5) 


``````````diff
diff --git a/llvm/include/llvm/TableGen/CodeGenHelpers.h b/llvm/include/llvm/TableGen/CodeGenHelpers.h
index 7dca6a051ba75..f9629236b9dfd 100644
--- a/llvm/include/llvm/TableGen/CodeGenHelpers.h
+++ b/llvm/include/llvm/TableGen/CodeGenHelpers.h
@@ -38,28 +38,29 @@ class IfDefEmitter {
 // namespace (empty for anonymous namespace) or nested namespace.
 class NamespaceEmitter {
 public:
-  NamespaceEmitter(raw_ostream &OS, StringRef Name) : OS(OS) {
-    emitNamespaceStarts(Name);
+  NamespaceEmitter(raw_ostream &OS, StringRef Name)
+      : Name(trim(Name).str()), OS(OS) {
+    OS << "namespace " << this->Name << " {\n";
   }
 
   ~NamespaceEmitter() { close(); }
 
   // Explicit function to close the namespace scopes.
   void close() {
-    for (StringRef NS : llvm::reverse(Namespaces))
-      OS << "} // namespace " << NS << "\n";
-    Namespaces.clear();
+    if (!Closed)
+      OS << "} // namespace " << Name << "\n";
+    Closed = true;
   }
 
 private:
-  void emitNamespaceStarts(StringRef Name) {
-    llvm::SplitString(Name, Namespaces, "::");
-    for (StringRef NS : Namespaces)
-      OS << "namespace " << NS << " {\n";
+  // Trim "::" prefix.
+  static StringRef trim(StringRef Name) {
+    Name.consume_front("::");
+    return Name;
   }
-
-  SmallVector<StringRef, 2> Namespaces;
+  std::string Name;
   raw_ostream &OS;
+  bool Closed = false;
 };
 
 } // end namespace llvm
diff --git a/mlir/test/mlir-tblgen/dialect.td b/mlir/test/mlir-tblgen/dialect.td
index f35ce345a90a8..9b454959a1da9 100644
--- a/mlir/test/mlir-tblgen/dialect.td
+++ b/mlir/test/mlir-tblgen/dialect.td
@@ -62,9 +62,14 @@ def E_SpecialNSOp : Op<E_Dialect, "special_ns_op", []> {
 // DEF: ::E::SPECIAL_NS::SpecialNSOp definitions
 
 // DECL-LABEL: GET_OP_CLASSES
+// DECL: namespace a {
 // DECL: a::SomeOp declarations
+// DECL: namespace BNS {
 // DECL: BNS::SomeOp declarations
+// DECL: namespace C::CC {
 // DECL: ::C::CC::SomeOp declarations
 // DECL: DSomeOp declarations
+// DECL: namespace ENS {
 // DECL: ENS::SomeOp declarations
+// DECL: namespace E::SPECIAL_NS {
 // DECL: ::E::SPECIAL_NS::SpecialNSOp declarations

``````````

</details>


https://github.com/llvm/llvm-project/pull/161958


More information about the llvm-commits mailing list