Skip to content

Commit

Permalink
Simplified special character check
Browse files Browse the repository at this point in the history
  • Loading branch information
timohl committed Jan 10, 2025
1 parent bbb0ca7 commit 21f52eb
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 5 deletions.
7 changes: 4 additions & 3 deletions include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,9 @@ class cpp_function : public function {
// signature. Using `@^`/`@$` we can force types to be arg/return types while `@!` pops
// back to the previous state.
std::stack<bool> is_return_value({false});
// The following characters have special meaning in the signature parsing. Literals
// containing these are escaped with `!`.
std::string special_chars("!@%{}-");
for (const auto *pc = text; *pc != '\0'; ++pc) {
const auto c = *pc;

Expand Down Expand Up @@ -498,9 +501,7 @@ class cpp_function : public function {
} else {
signature += detail::quote_cpp_type_name(detail::clean_type_id(t->name()));
}
} else if (c == '!'
&& (*(pc + 1) == '!' || *(pc + 1) == '@' || *(pc + 1) == '%'
|| *(pc + 1) == '{' || *(pc + 1) == '}' || *(pc + 1) == '-')) {
} else if (c == '!' && special_chars.find(*(pc + 1)) != std::string::npos) {
// typing::Literal escapes special characters with !
signature += *++pc;
} else if (c == '@') {
Expand Down
2 changes: 1 addition & 1 deletion tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -971,7 +971,7 @@ TEST_SUBMODULE(pytypes, m) {
.value("BLUE", literals::Color::BLUE);

m.def("annotate_literal", [](literals::LiteralFoo &o) -> py::object { return o; });
// Literal with `@`, `%`, `{`, and `}`
// 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; });
Expand Down
2 changes: 1 addition & 1 deletion tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1044,7 +1044,7 @@ 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["!"]'
Expand Down

0 comments on commit 21f52eb

Please sign in to comment.