Repository: amaranth-lang/amaranth (python)

Issue:
Unclear error message on `m.domains.cd_tx = ClockDomain()`
One could reasonably write the following code:

```py
m.domains.cd_tx = ClockDomain()
```

This fails with:

```
NameError: Clock domain name 'rx' must match name in `m.domains.cd_rx += ...` syntax
```

It fails because the `cd_` prefix is stripped by `ClockDomain()` but not `m.domains.x = `. The correct syntax is is:

```py
m.domains.cd_tx = ClockDomain()
```

This is a rather confusing diagnostic and should be improved.

Pull request description:
hdl._dsl: improve error message on `m.domains.cd_foo = ...`.
Fixes #1331.

Patch:
diff --git a/amaranth/hdl/_dsl.py b/amaranth/hdl/_dsl.py
index 9aee72a..5b24275 100644
--- a/amaranth/hdl/_dsl.py
+++ b/amaranth/hdl/_dsl.py
@@ -191,9 +191,11 @@ class _ModuleBuilderDomainSet:
             raise TypeError("Only clock domains may be added to `m.domains`, not {!r}"
                             .format(domain))
         if domain.name != name:
-            raise NameError("Clock domain name {!r} must match name in `m.domains.{} += ...` "
-                            "syntax"
-                            .format(domain.name, name))
+            if name == "cd_" + domain.name:
+                raise NameError(f"Domain name should not be prefixed with 'cd_' in `m.domains`, "
+                                f"use `m.domains.{domain.name} = ...` instead")
+            raise NameError(f"Clock domain name {domain.name!r} must match name in "
+                            f"`m.domains.{name} = ...` syntax")
         self._builder._add_domain(domain)
 
 


Test patch:
diff --git a/tests/test_hdl_dsl.py b/tests/test_hdl_dsl.py
index ca9c4f4..68a4522 100644
--- a/tests/test_hdl_dsl.py
+++ b/tests/test_hdl_dsl.py
@@ -930,7 +930,7 @@ class DSLTestCase(FHDLTestCase):
     def test_domain_add_wrong_name(self):
         m = Module()
         with self.assertRaisesRegex(NameError,
-                r"^Clock domain name 'bar' must match name in `m\.domains\.foo \+= \.\.\.` syntax$"):
+                r"^Clock domain name 'bar' must match name in `m\.domains\.foo = \.\.\.` syntax$"):
             m.domains.foo = ClockDomain("bar")
 
     def test_domain_add_wrong_duplicate(self):
@@ -968,3 +968,10 @@ class DSLTestCase(FHDLTestCase):
         )
         """)
         self.assertEqual(len(f2.subfragments), 0)
+
+    def test_bug_1331(self):
+        m = Module()
+        with self.assertRaisesRegex(NameError,
+                r"^Domain name should not be prefixed with 'cd_' in `m.domains`, "
+                r"use `m.domains.rx = ...` instead$"):
+            m.domains.cd_rx = ClockDomain()