Commit Graph
2 Commits
Author SHA1 Message Date
Jon Ross-Perkins 800e8fd55a Add braces for CARBON_KIND uses that lack them (#5882)
Also document why these are expected on `CARBON_KIND`. In
`kind_switch_test.cpp`, drop the `str` variable.

My recollection of the original discussion of `CARBON_KIND` is that it
should always have braces due to the risk of confusion for statement
interpretation, similar to a typical `if`/`else` but more subtle due to
the macro.

For example:

```
      case CARBON_KIND(int n):
        str << "int = " << n;
        return str.TakeStr();
```

is equivalent to:

```
      case CARBON_KIND(int n): {
          str << "int = " << n;
        }
        return str.TakeStr();
```

This happens to work in context because `str` isn't scoped, but a
trivial refactoring to move `RawStringOstream str;` the first statement
of the `case` would probably have non-obvious results. For example:

```
      case CARBON_KIND(int n):
        RawStringOstream str; // Valid name shadowing, destructed without use.
        str << "int = " << n; // Name lookup error on `n`.
        return str.TakeStr();
```
2025-07-30 18:56:39 +00:00
Dana JansensandRichard Smith b24944bfba Allow using CARBON_KIND_SWITCH on a std::variant (#5433)
We use CARBON_KIND_SWITCH for handling the output of TypeIterator in the
TypeStructureBuilder

Here is how the errors look when it is misused:
- If you don't cover ever type in the variant with a case
  ```
Enumeration value 'VariantTypeT1NotHandledInSwitch' not handled in
switch
  ```
Is attached to the CARBON_KIND_SWITCH() usage, the `T1` being a 0-based
index into the std::variant's type list, indicating which type was
missed.
- If you have a case for a type that is not in the variant
  ```
In template: constraints not satisfied for class template
'ValidCaseType' [with T = char]
  ... bunch of instantiation stuff ...
kind_switch.h(124, 12): Because 'char' does not satisfy
'TypeFoundInVariant'
  ```
Where `char` was the type I put in the `CARBON_KIND` macro, which was
not in the variant.
- If you have too many types in your variant (currently > 12)
  ```
In template: static assertion failed due to requirement 'sizeof...(Ts)
<= 12': CARBON_KIND_SWITCH supports std::variant with up to 12 types.
Add more if needed.
  ```
  Is attached to the CARBON_KIND_SWITCH() usage.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-05-12 16:26:55 +00:00