Skip to content

Commit 737ad61

Browse files
committed
Add an RFC for ValueCastable formatting.
1 parent 2c7ad0a commit 737ad61

File tree

1 file changed

+123
-0
lines changed

1 file changed

+123
-0
lines changed

text/0058-valuecastable-format.md

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
- Start Date: 2024-03-25
2+
- RFC PR: [amaranth-lang/rfcs#58](https://github.com/amaranth-lang/rfcs/pull/58)
3+
- Amaranth Issue: [amaranth-lang/amaranth#1243](https://github.com/amaranth-lang/amaranth/issues/1243)
4+
5+
# Core support for `ValueCastable` formatting
6+
7+
## Summary
8+
[summary]: #summary
9+
10+
`Format` hooks are added, allowing custom formatting to be implemented for `ValueCastable`s.
11+
12+
This RFC is only about adding hook support for custom `ShapeCastable`s. Providing actual formatting implementation for `lib.data` and `lib.enum` is left for a future RFC.
13+
14+
## Motivation
15+
[motivation]: #motivation
16+
17+
Custom types, like enums and data structures, will not make immediate sense to the user when printed as raw bit patterns. However, it is often desirable to print them out with the `Print` statement. Thus, an extension point for custom formatting needs to be added to the `Format` machinery.
18+
19+
## Guide-level explanation
20+
[guide-level-explanation]: #guide-level-explanation
21+
22+
`ShapeCastable` subtypes can define their own ways of formatting values by implementing the `format` hook:
23+
24+
```py
25+
class FixedPoint(ShapeCastable):
26+
...
27+
28+
def format(self, value, format_desc):
29+
if format_desc == "b":
30+
# Format a fixed-point value as binary.
31+
return Format("{value.int:b}.{value.fract:0{fract_bits}b}}", value=value, fract_bits=len(value.fract))
32+
elif format_desc == "x":
33+
# Format a fixed-point value as hexadecimal (very simplified implementation).
34+
assert len(value.fract) % 4 == 0
35+
return Format("{value.int:x}.{value.fract:0{fract_digits}x}}", value=value, fract_digits=len(value.fract) // 4)
36+
else:
37+
...
38+
39+
# A fixed-point number with 8 integer and 8 fractional bits.
40+
num = Signal(FixedPoint(8, 8))
41+
m.d.comb += [
42+
num.eq(0x1234)
43+
Print(Format("Value in binary: {:b}", num)),
44+
Print(Format("Value in hexadecimal: {:x}", num)),
45+
]
46+
```
47+
48+
prints:
49+
50+
```
51+
Value in binary: 00010010.00110100
52+
Value in hexadecimal: 12.34
53+
```
54+
55+
However, sometimes it is also useful to print the raw value of such a signal. A shorthand is provided for that purpose:
56+
57+
```py
58+
m.d.comb += Print(Format("Value: {num:x} (raw: {num!v:x})", num=num))
59+
```
60+
61+
```
62+
Value: 12.34 (raw: 1234)
63+
```
64+
65+
## Reference-level explanation
66+
[reference-level-explanation]: #reference-level-explanation
67+
68+
A new overridable method is added to `ShapeCastable`:
69+
70+
- `format(self, value: ValueCastable, format_desc: str) -> Format`
71+
72+
When a `ValueCastable` is formatted without specifying a conversion (ie. `"!r"` or `"!v"`):
73+
74+
- `shape()` is called
75+
- if the shape is a `ShapeCastable` and has a `format` method, the value-castable being formatted and the format descriptor (the part after `:` in `{}`, if any) are passed directly to `shape.format()`, and the result (which must be a `Format` object) is included directly in place of the format specifier
76+
- otherwise (the shape is a plain `Shape`, or doesn't have `format`), `Value.cast()` is called on the value-castable, and formatting proceeds as if it was a plain value
77+
78+
A new conversion, `!v`, is added to `Format` (with syntax analogous to `!r`). When specified, the value being formatted is converted through `Value.cast` before proceeding with further formatting. It can be used to print the raw value of value-castables. It is a no-op when used with a plain `Value`.
79+
80+
An implementation of `__format__` is added to the `ValueCastable` base class that always raises a `TypeError`, directing the user to `Format` instead (like the one that already exists on plain `Value`).
81+
82+
## Drawbacks
83+
[drawbacks]: #drawbacks
84+
85+
A new reserved name, `format`, is added to `ShapeCastable`, which is intended to be a fairly slim interface.
86+
87+
The `__format__` on `ValueCastable` is the first time we have a method with an actual implementation.
88+
89+
## Rationale and alternatives
90+
[rationale-and-alternatives]: #rationale-and-alternatives
91+
92+
The `format` hook is added on `ShapeCastable` instead of `ValueCastable`. This ensures that `ValueCastable`s without a custom shape automatically get plain formatting.
93+
94+
The default behavior proposed in this RFC ensures that a formatting implementation is always available, allowing generic code to print arbitrary values without worrying about an exception. Eg. something like `lib.fifo` could use debug prints when an element is added, automatically using rich formatting for shapes with `format`, while falling back to plain integers when rich formatting is not available.
95+
96+
alternative default behaviors possible are:
97+
98+
- raise `TypeError` (disallow formatting value-castables without explicitly implemented formatting)
99+
- no default, require every `ShapeCastable` to implement `format` (compatibility breaking)
100+
101+
To avoid reserving a name and interfering with user code, `format` could be renamed to `_amaranth_format`.
102+
103+
## Prior art
104+
[prior-art]: #prior-art
105+
106+
This RFC is modelled directly on the `__format__` extension point in Python.
107+
108+
## Unresolved questions
109+
[unresolved-questions]: #unresolved-questions
110+
111+
Bikeshed: what should `!v` be called? Alternatives proposed:
112+
113+
- `!v` (cast to value)
114+
- `!i` (print as integer)
115+
- `!n` (print as number)
116+
- `!R` (print raw)
117+
- `!l` (lower to a value)
118+
- `!av` (as value)
119+
120+
## Future possibilities
121+
[future-possibilities]: #future-possibilities
122+
123+
Actual formatting will need to be implemented for `lib.data` and `lib.enum`.

0 commit comments

Comments
 (0)