Error when passing StringRef to CARBON_DIAGNOSTIC. (#3431)

This gets to a lifetime subtlety, particularly with things like the
sorting diagnostic consumer that delay output. In order to reduce the
chance of accidental references, disallow StringRef in the diagnostics.

For example:

```
./toolchain/diagnostics/diagnostic_emitter.h:162:5: error: static_assert failed due to requirement '!std::is_same_v<llvm::StringRef, llvm::StringRef>' "Use std::string or llvm::StringLiteral for diagnostic lifetimes."
    static_assert(
    ^
toolchain/check/convert.cpp:477:11: note: in instantiation of member function 'Carbon::Internal::DiagnosticBase<std::string, std::string, llvm::StringRef>::DiagnosticBase' requested here
          CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
          ^
./toolchain/diagnostics/diagnostic_emitter.h:47:7: note: expanded from macro 'CARBON_DIAGNOSTIC'
      ::Carbon::Internal::DiagnosticBase<__VA_ARGS__>(        \
      ^
```

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
This commit is contained in:
Jon Ross-Perkins
2023-11-29 17:04:11 +00:00
committed by GitHub
co-authored by Chandler Carruth
parent 161f46ed37
commit 0c0998d7cd
15 changed files with 46 additions and 38 deletions
+9 -5
View File
@@ -29,11 +29,15 @@ static auto HandleBraceExprParamError(Context& context,
bool is_unknown = param_finish_state == State::BraceExprParamFinishAsUnknown;
CARBON_CHECK(is_type || is_value || is_unknown);
CARBON_DIAGNOSTIC(ExpectedStructLiteralField, Error, "Expected {0}{1}{2}.",
llvm::StringRef, llvm::StringRef, llvm::StringRef);
context.emitter().Emit(*context.position(), ExpectedStructLiteralField,
(is_type || is_unknown) ? "`.field: field_type`" : "",
is_unknown ? " or " : "",
(is_value || is_unknown) ? "`.field = value`" : "");
llvm::StringLiteral, llvm::StringLiteral,
llvm::StringLiteral);
context.emitter().Emit(
*context.position(), ExpectedStructLiteralField,
(is_type || is_unknown) ? llvm::StringLiteral("`.field: field_type`")
: llvm::StringLiteral(""),
is_unknown ? llvm::StringLiteral(" or ") : llvm::StringLiteral(""),
(is_value || is_unknown) ? llvm::StringLiteral("`.field = value`")
: llvm::StringLiteral(""));
state.state = param_finish_state;
state.has_error = true;