Skip to content

Commit

Permalink
Emit C++ string literals for HILTI string literals.
Browse files Browse the repository at this point in the history
When emitting literals for HILTI strings (string ctors) we would
previously explicitly force creation of `std::string`. This was almost
always an unnecessary pessimisation over emitting string literals since
even if their C++ uses expected `std::string` string literals can
convert to this type implicitly; at the same time it made it impossible
to make effective use of APIs accepting `std::string_view`.

With this patch we now emit C++ string literals for HILTI string
literals.
  • Loading branch information
bbannier committed Nov 17, 2023
1 parent c3e3e59 commit 2a2251e
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion hilti/toolchain/src/compiler/codegen/ctors.cc
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,21 @@ struct Visitor : hilti::visitor::PreOrder<cxx::Expression, Visitor> {
return fmt("::hilti::rt::Stream(\"%s\"_b)", util::escapeBytesForCxx(n.value()));
}

result_t operator()(const ctor::String& n) { return fmt("std::string(\"%s\")", util::escapeUTF8(n.value(), true)); }
result_t operator()(const ctor::String& n) {
// We emit string constructors for both user-provided literals and
// generated strings, e.g., static error messages or identifiers. Only
// user-provided literals need to behave like actual our runtime string
// type `std::string` since they e.g., need to be usable with functions
// expecting that type or might need to be mutable; generated string
// OTOH are static and only used with our internal APIs which we can
// make usable with actual literals, and we can avoid allocating owning
// mutable strings for them.
bool is_spelled = n.meta().location().file().empty();
if ( is_spelled )
return fmt("std::string_view(\"%s\")", util::escapeUTF8(n.value(), true));
else
return fmt("std::string(\"%s\")", util::escapeUTF8(n.value(), true));
}

result_t operator()(const ctor::Tuple& n) {
return fmt("std::make_tuple(%s)",
Expand Down

0 comments on commit 2a2251e

Please sign in to comment.