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-PerkinsandChandler Carruth authored and GitHub committed 2023-11-29 17:04:11 +00:00
1 parent 161f46ed37
commit 0c0998d7cd
15 files changed
+46 -38

No files matched your search

+4 -3
View File
@@ -68,11 +68,12 @@ auto HandlePatternBinding(Context& context, Parse::Node parse_node) -> bool {
auto enclosing_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
if (!context.TryToCompleteType(cast_type_id, [&] {
CARBON_DIAGNOSTIC(IncompleteTypeInVarDecl, Error,
"{0} has incomplete type `{1}`.", llvm::StringRef,
std::string);
"{0} has incomplete type `{1}`.",
llvm::StringLiteral, std::string);
return context.emitter().Build(
type_node_copy, IncompleteTypeInVarDecl,
enclosing_class_decl ? "Field" : "Variable",
enclosing_class_decl ? llvm::StringLiteral("Field")
: llvm::StringLiteral("Variable"),
context.sem_ir().StringifyType(cast_type_id, true));
})) {
cast_type_id = SemIR::TypeId::Error;