mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-10-05 22:02:55 +01:00
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();
```
This commit is contained in:
@@ -16,36 +16,33 @@ namespace {
|
||||
|
||||
TEST(KindSwitch, Variant) {
|
||||
auto f = [](std::variant<int, float, char> v) -> std::string {
|
||||
RawStringOstream str;
|
||||
CARBON_KIND_SWITCH(v) {
|
||||
case CARBON_KIND(int n):
|
||||
str << "int = " << n;
|
||||
return str.TakeStr();
|
||||
case CARBON_KIND(float f):
|
||||
str << "float = " << f;
|
||||
return str.TakeStr();
|
||||
case CARBON_KIND(char c):
|
||||
str << "char = " << c;
|
||||
return str.TakeStr();
|
||||
case CARBON_KIND(int n): {
|
||||
return llvm::formatv("int = {0}", n);
|
||||
}
|
||||
case CARBON_KIND(float f): {
|
||||
return llvm::formatv("float = {0}", f);
|
||||
}
|
||||
case CARBON_KIND(char c): {
|
||||
return llvm::formatv("char = {0}", c);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
EXPECT_EQ(f(int{1}), "int = 1");
|
||||
EXPECT_EQ(f(float{2}), "float = 2.000000e+00");
|
||||
EXPECT_EQ(f(float{2}), "float = 2.00");
|
||||
EXPECT_EQ(f(char{'h'}), "char = h");
|
||||
}
|
||||
|
||||
TEST(KindSwitch, VariantUnusedValue) {
|
||||
auto f = [](std::variant<int, float> v) -> std::string {
|
||||
RawStringOstream str;
|
||||
CARBON_KIND_SWITCH(v) {
|
||||
case CARBON_KIND(int n):
|
||||
str << "int = " << n;
|
||||
return str.TakeStr();
|
||||
case CARBON_KIND(int n): {
|
||||
return llvm::formatv("int = {0}", n);
|
||||
}
|
||||
case CARBON_KIND(float _):
|
||||
// The float value is not used, we see that using `_` works.
|
||||
str << "float";
|
||||
return str.TakeStr();
|
||||
return "float";
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user