Skip to content

Commit

Permalink
Added test for Literal with ! and changed StringLiteral template pa…
Browse files Browse the repository at this point in the history
…ram name
  • Loading branch information
timohl committed Jan 9, 2025
1 parent 8df42eb commit 9867800
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
6 changes: 3 additions & 3 deletions include/pybind11/typing.h
Original file line number Diff line number Diff line change
Expand Up @@ -256,14 +256,14 @@ struct handle_type_name<typing::Never> {
};

#if defined(PYBIND11_TYPING_H_HAS_STRING_LITERAL)
template <typing::StringLiteral str>
template <typing::StringLiteral StrLit>
consteval auto sanitize_string_literal() {
constexpr std::string_view v(str.name);
constexpr std::string_view v(StrLit.name);
char result[v.size() + std::ranges::count(v, '!') + std::ranges::count(v, '@')
+ std::ranges::count(v, '%') + std::ranges::count(v, '{')
+ std::ranges::count(v, '}') + 1];
size_t i = 0;
for (auto c : str.name) {
for (auto c : StrLit.name) {
if (c == '!') {
result[i++] = '!';
result[i++] = '!';
Expand Down
1 change: 1 addition & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -972,6 +972,7 @@ TEST_SUBMODULE(pytypes, m) {

m.def("annotate_literal", [](literals::LiteralFoo &o) -> py::object { return o; });
// Literal with `@`, `%`, `{`, and `}`
m.def("identity_literal_exclamation", [](const py::typing::Literal<"\"!\""> &x) { return x; });
m.def("identity_literal_at", [](const py::typing::Literal<"\"@\""> &x) { return x; });
m.def("identity_literal_percent", [](const py::typing::Literal<"\"%\""> &x) { return x; });
m.def("identity_literal_curly_open", [](const py::typing::Literal<"\"{\""> &x) { return x; });
Expand Down
6 changes: 5 additions & 1 deletion tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1044,7 +1044,11 @@ def test_literal(doc):
doc(m.annotate_literal)
== 'annotate_literal(arg0: Literal[26, 0x1A, "hello world", b"hello world", u"hello world", True, Color.RED, None]) -> object'
)
# The characters @, %, and {} are used in the signature parser as special characters, but Literal should escape those for the parser to work.
# The characters !, @, %, and {} are used in the signature parser as special characters, but Literal should escape those for the parser to work.
assert (
doc(m.identity_literal_exclamation)
== 'identity_literal_exclamation(arg0: Literal["!"]) -> Literal["!"]'
)
assert (
doc(m.identity_literal_at)
== 'identity_literal_at(arg0: Literal["@"]) -> Literal["@"]'
Expand Down

0 comments on commit 9867800

Please sign in to comment.