Commit ddbc74c6 authored by Ralf W. Grosse-Kunstleve's avatar Ralf W. Grosse-Kunstleve Committed by Ralf W. Grosse-Kunstleve
Browse files

Adding .clang-tidy readability-braces-around-statements option.

clang-tidy automatic changes. NO manual changes.
parent 8581584e
...@@ -52,14 +52,16 @@ template <typename Type, typename Key> struct set_caster { ...@@ -52,14 +52,16 @@ template <typename Type, typename Key> struct set_caster {
using key_conv = make_caster<Key>; using key_conv = make_caster<Key>;
bool load(handle src, bool convert) { bool load(handle src, bool convert) {
if (!isinstance<pybind11::set>(src)) if (!isinstance<pybind11::set>(src)) {
return false; return false;
}
auto s = reinterpret_borrow<pybind11::set>(src); auto s = reinterpret_borrow<pybind11::set>(src);
value.clear(); value.clear();
for (auto entry : s) { for (auto entry : s) {
key_conv conv; key_conv conv;
if (!conv.load(entry, convert)) if (!conv.load(entry, convert)) {
return false; return false;
}
value.insert(cast_op<Key &&>(std::move(conv))); value.insert(cast_op<Key &&>(std::move(conv)));
} }
return true; return true;
...@@ -67,13 +69,15 @@ template <typename Type, typename Key> struct set_caster { ...@@ -67,13 +69,15 @@ template <typename Type, typename Key> struct set_caster {
template <typename T> template <typename T>
static handle cast(T &&src, return_value_policy policy, handle parent) { static handle cast(T &&src, return_value_policy policy, handle parent) {
if (!std::is_lvalue_reference<T>::value) if (!std::is_lvalue_reference<T>::value) {
policy = return_value_policy_override<Key>::policy(policy); policy = return_value_policy_override<Key>::policy(policy);
}
pybind11::set s; pybind11::set s;
for (auto &&value : src) { for (auto &&value : src) {
auto value_ = reinterpret_steal<object>(key_conv::cast(forward_like<T>(value), policy, parent)); auto value_ = reinterpret_steal<object>(key_conv::cast(forward_like<T>(value), policy, parent));
if (!value_ || !s.add(value_)) if (!value_ || !s.add(value_)) {
return handle(); return handle();
}
} }
return s.release(); return s.release();
} }
...@@ -86,16 +90,17 @@ template <typename Type, typename Key, typename Value> struct map_caster { ...@@ -86,16 +90,17 @@ template <typename Type, typename Key, typename Value> struct map_caster {
using value_conv = make_caster<Value>; using value_conv = make_caster<Value>;
bool load(handle src, bool convert) { bool load(handle src, bool convert) {
if (!isinstance<dict>(src)) if (!isinstance<dict>(src)) {
return false; return false;
}
auto d = reinterpret_borrow<dict>(src); auto d = reinterpret_borrow<dict>(src);
value.clear(); value.clear();
for (auto it : d) { for (auto it : d) {
key_conv kconv; key_conv kconv;
value_conv vconv; value_conv vconv;
if (!kconv.load(it.first.ptr(), convert) || if (!kconv.load(it.first.ptr(), convert) || !vconv.load(it.second.ptr(), convert)) {
!vconv.load(it.second.ptr(), convert))
return false; return false;
}
value.emplace(cast_op<Key &&>(std::move(kconv)), cast_op<Value &&>(std::move(vconv))); value.emplace(cast_op<Key &&>(std::move(kconv)), cast_op<Value &&>(std::move(vconv)));
} }
return true; return true;
...@@ -113,8 +118,9 @@ template <typename Type, typename Key, typename Value> struct map_caster { ...@@ -113,8 +118,9 @@ template <typename Type, typename Key, typename Value> struct map_caster {
for (auto &&kv : src) { for (auto &&kv : src) {
auto key = reinterpret_steal<object>(key_conv::cast(forward_like<T>(kv.first), policy_key, parent)); auto key = reinterpret_steal<object>(key_conv::cast(forward_like<T>(kv.first), policy_key, parent));
auto value = reinterpret_steal<object>(value_conv::cast(forward_like<T>(kv.second), policy_value, parent)); auto value = reinterpret_steal<object>(value_conv::cast(forward_like<T>(kv.second), policy_value, parent));
if (!key || !value) if (!key || !value) {
return handle(); return handle();
}
d[key] = value; d[key] = value;
} }
return d.release(); return d.release();
...@@ -127,15 +133,17 @@ template <typename Type, typename Value> struct list_caster { ...@@ -127,15 +133,17 @@ template <typename Type, typename Value> struct list_caster {
using value_conv = make_caster<Value>; using value_conv = make_caster<Value>;
bool load(handle src, bool convert) { bool load(handle src, bool convert) {
if (!isinstance<sequence>(src) || isinstance<bytes>(src) || isinstance<str>(src)) if (!isinstance<sequence>(src) || isinstance<bytes>(src) || isinstance<str>(src)) {
return false; return false;
}
auto s = reinterpret_borrow<sequence>(src); auto s = reinterpret_borrow<sequence>(src);
value.clear(); value.clear();
reserve_maybe(s, &value); reserve_maybe(s, &value);
for (auto it : s) { for (auto it : s) {
value_conv conv; value_conv conv;
if (!conv.load(it, convert)) if (!conv.load(it, convert)) {
return false; return false;
}
value.push_back(cast_op<Value &&>(std::move(conv))); value.push_back(cast_op<Value &&>(std::move(conv)));
} }
return true; return true;
...@@ -153,14 +161,16 @@ private: ...@@ -153,14 +161,16 @@ private:
public: public:
template <typename T> template <typename T>
static handle cast(T &&src, return_value_policy policy, handle parent) { static handle cast(T &&src, return_value_policy policy, handle parent) {
if (!std::is_lvalue_reference<T>::value) if (!std::is_lvalue_reference<T>::value) {
policy = return_value_policy_override<Value>::policy(policy); policy = return_value_policy_override<Value>::policy(policy);
}
list l(src.size()); list l(src.size());
ssize_t index = 0; ssize_t index = 0;
for (auto &&value : src) { for (auto &&value : src) {
auto value_ = reinterpret_steal<object>(value_conv::cast(forward_like<T>(value), policy, parent)); auto value_ = reinterpret_steal<object>(value_conv::cast(forward_like<T>(value), policy, parent));
if (!value_) if (!value_) {
return handle(); return handle();
}
PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference
} }
return l.release(); return l.release();
...@@ -184,8 +194,9 @@ template <typename ArrayType, typename Value, bool Resizable, size_t Size = 0> s ...@@ -184,8 +194,9 @@ template <typename ArrayType, typename Value, bool Resizable, size_t Size = 0> s
private: private:
template <bool R = Resizable> template <bool R = Resizable>
bool require_size(enable_if_t<R, size_t> size) { bool require_size(enable_if_t<R, size_t> size) {
if (value.size() != size) if (value.size() != size) {
value.resize(size); value.resize(size);
}
return true; return true;
} }
template <bool R = Resizable> template <bool R = Resizable>
...@@ -195,16 +206,19 @@ private: ...@@ -195,16 +206,19 @@ private:
public: public:
bool load(handle src, bool convert) { bool load(handle src, bool convert) {
if (!isinstance<sequence>(src)) if (!isinstance<sequence>(src)) {
return false; return false;
}
auto l = reinterpret_borrow<sequence>(src); auto l = reinterpret_borrow<sequence>(src);
if (!require_size(l.size())) if (!require_size(l.size())) {
return false; return false;
}
size_t ctr = 0; size_t ctr = 0;
for (auto it : l) { for (auto it : l) {
value_conv conv; value_conv conv;
if (!conv.load(it, convert)) if (!conv.load(it, convert)) {
return false; return false;
}
value[ctr++] = cast_op<Value &&>(std::move(conv)); value[ctr++] = cast_op<Value &&>(std::move(conv));
} }
return true; return true;
...@@ -216,8 +230,9 @@ public: ...@@ -216,8 +230,9 @@ public:
ssize_t index = 0; ssize_t index = 0;
for (auto &&value : src) { for (auto &&value : src) {
auto value_ = reinterpret_steal<object>(value_conv::cast(forward_like<T>(value), policy, parent)); auto value_ = reinterpret_steal<object>(value_conv::cast(forward_like<T>(value), policy, parent));
if (!value_) if (!value_) {
return handle(); return handle();
}
PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference PyList_SET_ITEM(l.ptr(), index++, value_.release().ptr()); // steals a reference
} }
return l.release(); return l.release();
...@@ -250,8 +265,9 @@ template<typename Type, typename Value = typename Type::value_type> struct optio ...@@ -250,8 +265,9 @@ template<typename Type, typename Value = typename Type::value_type> struct optio
template <typename T> template <typename T>
static handle cast(T &&src, return_value_policy policy, handle parent) { static handle cast(T &&src, return_value_policy policy, handle parent) {
if (!src) if (!src) {
return none().inc_ref(); return none().inc_ref();
}
if (!std::is_lvalue_reference<T>::value) { if (!std::is_lvalue_reference<T>::value) {
policy = return_value_policy_override<Value>::policy(policy); policy = return_value_policy_override<Value>::policy(policy);
} }
...@@ -266,8 +282,9 @@ template<typename Type, typename Value = typename Type::value_type> struct optio ...@@ -266,8 +282,9 @@ template<typename Type, typename Value = typename Type::value_type> struct optio
return true; // default-constructed value is already empty return true; // default-constructed value is already empty
} }
value_conv inner_caster; value_conv inner_caster;
if (!inner_caster.load(src, convert)) if (!inner_caster.load(src, convert)) {
return false; return false;
}
value.emplace(cast_op<Value &&>(std::move(inner_caster))); value.emplace(cast_op<Value &&>(std::move(inner_caster)));
return true; return true;
...@@ -341,8 +358,9 @@ struct variant_caster<V<Ts...>> { ...@@ -341,8 +358,9 @@ struct variant_caster<V<Ts...>> {
// E.g. `py::int_(1).cast<variant<double, int>>()` needs to fill the `int` // E.g. `py::int_(1).cast<variant<double, int>>()` needs to fill the `int`
// slot of the variant. Without two-pass loading `double` would be filled // slot of the variant. Without two-pass loading `double` would be filled
// because it appears first and a conversion is possible. // because it appears first and a conversion is possible.
if (convert && load_alternative(src, false, type_list<Ts...>{})) if (convert && load_alternative(src, false, type_list<Ts...>{})) {
return true; return true;
}
return load_alternative(src, convert, type_list<Ts...>{}); return load_alternative(src, convert, type_list<Ts...>{});
} }
......
...@@ -87,10 +87,11 @@ void vector_if_equal_operator(enable_if_t<is_comparable<Vector>::value, Class_> ...@@ -87,10 +87,11 @@ void vector_if_equal_operator(enable_if_t<is_comparable<Vector>::value, Class_>
cl.def("remove", [](Vector &v, const T &x) { cl.def("remove", [](Vector &v, const T &x) {
auto p = std::find(v.begin(), v.end(), x); auto p = std::find(v.begin(), v.end(), x);
if (p != v.end()) if (p != v.end()) {
v.erase(p); v.erase(p);
else } else {
throw value_error(); throw value_error();
}
}, },
arg("x"), arg("x"),
"Remove the first item from the list whose value is x. " "Remove the first item from the list whose value is x. "
...@@ -116,10 +117,12 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t ...@@ -116,10 +117,12 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t
using DiffType = typename Vector::difference_type; using DiffType = typename Vector::difference_type;
auto wrap_i = [](DiffType i, SizeType n) { auto wrap_i = [](DiffType i, SizeType n) {
if (i < 0) if (i < 0) {
i += n; i += n;
if (i < 0 || (SizeType)i >= n) }
if (i < 0 || (SizeType) i >= n) {
throw index_error(); throw index_error();
}
return i; return i;
}; };
...@@ -131,8 +134,9 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t ...@@ -131,8 +134,9 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t
cl.def(init([](const iterable &it) { cl.def(init([](const iterable &it) {
auto v = std::unique_ptr<Vector>(new Vector()); auto v = std::unique_ptr<Vector>(new Vector());
v->reserve(len_hint(it)); v->reserve(len_hint(it));
for (handle h : it) for (handle h : it) {
v->push_back(h.cast<T>()); v->push_back(h.cast<T>());
}
return v.release(); return v.release();
})); }));
...@@ -177,26 +181,29 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t ...@@ -177,26 +181,29 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t
cl.def("insert", cl.def("insert",
[](Vector &v, DiffType i, const T &x) { [](Vector &v, DiffType i, const T &x) {
// Can't use wrap_i; i == v.size() is OK // Can't use wrap_i; i == v.size() is OK
if (i < 0) if (i < 0) {
i += v.size(); i += v.size();
if (i < 0 || (SizeType)i > v.size()) }
if (i < 0 || (SizeType) i > v.size()) {
throw index_error(); throw index_error();
}
v.insert(v.begin() + i, x); v.insert(v.begin() + i, x);
}, },
arg("i") , arg("x"), arg("i") , arg("x"),
"Insert an item at a given position." "Insert an item at a given position."
); );
cl.def("pop", cl.def(
"pop",
[](Vector &v) { [](Vector &v) {
if (v.empty()) if (v.empty()) {
throw index_error(); throw index_error();
}
T t = std::move(v.back()); T t = std::move(v.back());
v.pop_back(); v.pop_back();
return t; return t;
}, },
"Remove and return the last item" "Remove and return the last item");
);
cl.def("pop", cl.def("pop",
[wrap_i](Vector &v, DiffType i) { [wrap_i](Vector &v, DiffType i) {
...@@ -222,8 +229,9 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t ...@@ -222,8 +229,9 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t
[](const Vector &v, slice slice) -> Vector * { [](const Vector &v, slice slice) -> Vector * {
size_t start = 0, stop = 0, step = 0, slicelength = 0; size_t start = 0, stop = 0, step = 0, slicelength = 0;
if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
throw error_already_set(); throw error_already_set();
}
auto *seq = new Vector(); auto *seq = new Vector();
seq->reserve((size_t) slicelength); seq->reserve((size_t) slicelength);
...@@ -241,11 +249,14 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t ...@@ -241,11 +249,14 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t
"__setitem__", "__setitem__",
[](Vector &v, slice slice, const Vector &value) { [](Vector &v, slice slice, const Vector &value) {
size_t start = 0, stop = 0, step = 0, slicelength = 0; size_t start = 0, stop = 0, step = 0, slicelength = 0;
if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
throw error_already_set(); throw error_already_set();
}
if (slicelength != value.size()) if (slicelength != value.size()) {
throw std::runtime_error("Left and right hand size of slice assignment have different sizes!"); throw std::runtime_error(
"Left and right hand size of slice assignment have different sizes!");
}
for (size_t i=0; i<slicelength; ++i) { for (size_t i=0; i<slicelength; ++i) {
v[start] = value[i]; v[start] = value[i];
...@@ -267,8 +278,9 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t ...@@ -267,8 +278,9 @@ void vector_modifiers(enable_if_t<is_copy_constructible<typename Vector::value_t
[](Vector &v, slice slice) { [](Vector &v, slice slice) {
size_t start = 0, stop = 0, step = 0, slicelength = 0; size_t start = 0, stop = 0, step = 0, slicelength = 0;
if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
throw error_already_set(); throw error_already_set();
}
if (step == 1 && false) { if (step == 1 && false) {
v.erase(v.begin() + (DiffType) start, v.begin() + DiffType(start + slicelength)); v.erase(v.begin() + (DiffType) start, v.begin() + DiffType(start + slicelength));
...@@ -296,10 +308,12 @@ void vector_accessor(enable_if_t<!vector_needs_copy<Vector>::value, Class_> &cl) ...@@ -296,10 +308,12 @@ void vector_accessor(enable_if_t<!vector_needs_copy<Vector>::value, Class_> &cl)
using ItType = typename Vector::iterator; using ItType = typename Vector::iterator;
auto wrap_i = [](DiffType i, SizeType n) { auto wrap_i = [](DiffType i, SizeType n) {
if (i < 0) if (i < 0) {
i += n; i += n;
if (i < 0 || (SizeType)i >= n) }
if (i < 0 || (SizeType) i >= n) {
throw index_error(); throw index_error();
}
return i; return i;
}; };
...@@ -328,15 +342,15 @@ void vector_accessor(enable_if_t<vector_needs_copy<Vector>::value, Class_> &cl) ...@@ -328,15 +342,15 @@ void vector_accessor(enable_if_t<vector_needs_copy<Vector>::value, Class_> &cl)
using SizeType = typename Vector::size_type; using SizeType = typename Vector::size_type;
using DiffType = typename Vector::difference_type; using DiffType = typename Vector::difference_type;
using ItType = typename Vector::iterator; using ItType = typename Vector::iterator;
cl.def("__getitem__", cl.def("__getitem__", [](const Vector &v, DiffType i) -> T {
[](const Vector &v, DiffType i) -> T { if (i < 0 && (i += v.size()) < 0) {
if (i < 0 && (i += v.size()) < 0) throw index_error();
throw index_error();
if ((SizeType)i >= v.size())
throw index_error();
return v[(SizeType)i];
} }
); if ((SizeType) i >= v.size()) {
throw index_error();
}
return v[(SizeType) i];
});
cl.def("__iter__", cl.def("__iter__",
[](Vector &v) { [](Vector &v) {
...@@ -358,8 +372,9 @@ template <typename Vector, typename Class_> auto vector_if_insertion_operator(Cl ...@@ -358,8 +372,9 @@ template <typename Vector, typename Class_> auto vector_if_insertion_operator(Cl
s << name << '['; s << name << '[';
for (size_type i=0; i < v.size(); ++i) { for (size_type i=0; i < v.size(); ++i) {
s << v[i]; s << v[i];
if (i != v.size() - 1) if (i != v.size() - 1) {
s << ", "; s << ", ";
}
} }
s << ']'; s << ']';
return s.str(); return s.str();
...@@ -402,10 +417,14 @@ void vector_buffer_impl(Class_& cl, std::true_type) { ...@@ -402,10 +417,14 @@ void vector_buffer_impl(Class_& cl, std::true_type) {
cl.def(init([](const buffer &buf) { cl.def(init([](const buffer &buf) {
auto info = buf.request(); auto info = buf.request();
if (info.ndim != 1 || info.strides[0] % static_cast<ssize_t>(sizeof(T))) if (info.ndim != 1 || info.strides[0] % static_cast<ssize_t>(sizeof(T))) {
throw type_error("Only valid 1D buffers can be copied to a vector"); throw type_error("Only valid 1D buffers can be copied to a vector");
if (!detail::compare_buffer_info<T>::compare(info) || (ssize_t) sizeof(T) != info.itemsize) }
throw type_error("Format mismatch (Python: " + info.format + " C++: " + format_descriptor<T>::format() + ")"); if (!detail::compare_buffer_info<T>::compare(info)
|| (ssize_t) sizeof(T) != info.itemsize) {
throw type_error("Format mismatch (Python: " + info.format
+ " C++: " + format_descriptor<T>::format() + ")");
}
T *p = static_cast<T*>(info.ptr); T *p = static_cast<T*>(info.ptr);
ssize_t step = info.strides[0] / static_cast<ssize_t>(sizeof(T)); ssize_t step = info.strides[0] / static_cast<ssize_t>(sizeof(T));
...@@ -415,8 +434,9 @@ void vector_buffer_impl(Class_& cl, std::true_type) { ...@@ -415,8 +434,9 @@ void vector_buffer_impl(Class_& cl, std::true_type) {
} }
Vector vec; Vector vec;
vec.reserve((size_t) info.shape[0]); vec.reserve((size_t) info.shape[0]);
for (; p != end; p += step) for (; p != end; p += step) {
vec.push_back(*p); vec.push_back(*p);
}
return vec; return vec;
})); }));
...@@ -545,8 +565,11 @@ void map_assignment(enable_if_t<is_copy_assignable<typename Map::mapped_type>::v ...@@ -545,8 +565,11 @@ void map_assignment(enable_if_t<is_copy_assignable<typename Map::mapped_type>::v
cl.def("__setitem__", cl.def("__setitem__",
[](Map &m, const KeyType &k, const MappedType &v) { [](Map &m, const KeyType &k, const MappedType &v) {
auto it = m.find(k); auto it = m.find(k);
if (it != m.end()) it->second = v; if (it != m.end()) {
else m.emplace(k, v); it->second = v;
} else {
m.emplace(k, v);
}
} }
); );
} }
...@@ -583,8 +606,9 @@ template <typename Map, typename Class_> auto map_if_insertion_operator(Class_ & ...@@ -583,8 +606,9 @@ template <typename Map, typename Class_> auto map_if_insertion_operator(Class_ &
s << name << '{'; s << name << '{';
bool f = false; bool f = false;
for (auto const &kv : m) { for (auto const &kv : m) {
if (f) if (f) {
s << ", "; s << ", ";
}
s << kv.first << ": " << kv.second; s << kv.first << ": " << kv.second;
f = true; f = true;
} }
...@@ -675,8 +699,9 @@ class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args&&. ...@@ -675,8 +699,9 @@ class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args&&.
cl.def("__getitem__", cl.def("__getitem__",
[](Map &m, const KeyType &k) -> MappedType & { [](Map &m, const KeyType &k) -> MappedType & {
auto it = m.find(k); auto it = m.find(k);
if (it == m.end()) if (it == m.end()) {
throw key_error(); throw key_error();
}
return it->second; return it->second;
}, },
return_value_policy::reference_internal // ref + keepalive return_value_policy::reference_internal // ref + keepalive
...@@ -685,8 +710,9 @@ class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args&&. ...@@ -685,8 +710,9 @@ class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args&&.
cl.def("__contains__", cl.def("__contains__",
[](Map &m, const KeyType &k) -> bool { [](Map &m, const KeyType &k) -> bool {
auto it = m.find(k); auto it = m.find(k);
if (it == m.end()) if (it == m.end()) {
return false; return false;
}
return true; return true;
} }
); );
...@@ -699,8 +725,9 @@ class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args&&. ...@@ -699,8 +725,9 @@ class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args&&.
cl.def("__delitem__", cl.def("__delitem__",
[](Map &m, const KeyType &k) { [](Map &m, const KeyType &k) {
auto it = m.find(k); auto it = m.find(k);
if (it == m.end()) if (it == m.end()) {
throw key_error(); throw key_error();
}
m.erase(it); m.erase(it);
} }
); );
...@@ -717,8 +744,9 @@ class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args&&. ...@@ -717,8 +744,9 @@ class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args&&.
keys_view.def("__contains__", keys_view.def("__contains__",
[](KeysView &view, const KeyType &k) -> bool { [](KeysView &view, const KeyType &k) -> bool {
auto it = view.map.find(k); auto it = view.map.find(k);
if (it == view.map.end()) if (it == view.map.end()) {
return false; return false;
}
return true; return true;
} }
); );
......
...@@ -101,10 +101,11 @@ public: ...@@ -101,10 +101,11 @@ public:
} }
void destroyed(void *inst) { void destroyed(void *inst) {
if (--_instances[inst] < 0) if (--_instances[inst] < 0) {
throw std::runtime_error("cstats.destroyed() called with unknown " throw std::runtime_error("cstats.destroyed() called with unknown "
"instance; potential double-destruction " "instance; potential double-destruction "
"or a missing cstats.created()"); "or a missing cstats.created()");
}
} }
static void gc() { static void gc() {
...@@ -127,9 +128,11 @@ public: ...@@ -127,9 +128,11 @@ public:
int alive() { int alive() {
gc(); gc();
int total = 0; int total = 0;
for (const auto &p : _instances) for (const auto &p : _instances) {
if (p.second > 0) if (p.second > 0) {
total += p.second; total += p.second;
}
}
return total; return total;
} }
...@@ -145,7 +148,9 @@ public: ...@@ -145,7 +148,9 @@ public:
// Move out stored values // Move out stored values
py::list values() { py::list values() {
py::list l; py::list l;
for (const auto &v : _values) l.append(py::cast(v)); for (const auto &v : _values) {
l.append(py::cast(v));
}
_values.clear(); _values.clear();
return l; return l;
} }
...@@ -181,7 +186,9 @@ public: ...@@ -181,7 +186,9 @@ public:
} }
} }
catch (const std::out_of_range&) {} catch (const std::out_of_range&) {}
if (!t1) throw std::runtime_error("Unknown class passed to ConstructorStats::get()"); if (!t1) {
throw std::runtime_error("Unknown class passed to ConstructorStats::get()");
}
auto &cs1 = get(*t1); auto &cs1 = get(*t1);
// If we have both a t1 and t2 match, one is probably the trampoline class; return whichever // If we have both a t1 and t2 match, one is probably the trampoline class; return whichever
// has more constructions (typically one or the other will be 0) // has more constructions (typically one or the other will be 0)
...@@ -189,7 +196,9 @@ public: ...@@ -189,7 +196,9 @@ public:
auto &cs2 = get(*t2); auto &cs2 = get(*t2);
int cs1_total = cs1.default_constructions + cs1.copy_constructions + cs1.move_constructions + (int) cs1._values.size(); int cs1_total = cs1.default_constructions + cs1.copy_constructions + cs1.move_constructions + (int) cs1._values.size();
int cs2_total = cs2.default_constructions + cs2.copy_constructions + cs2.move_constructions + (int) cs2._values.size(); int cs2_total = cs2.default_constructions + cs2.copy_constructions + cs2.move_constructions + (int) cs2._values.size();
if (cs2_total > cs1_total) return cs2; if (cs2_total > cs1_total) {
return cs2;
}
} }
return cs1; return cs1;
} }
......
...@@ -27,10 +27,11 @@ public: ...@@ -27,10 +27,11 @@ public:
*/ */
void decRef(bool dealloc = true) const { void decRef(bool dealloc = true) const {
--m_refCount; --m_refCount;
if (m_refCount == 0 && dealloc) if (m_refCount == 0 && dealloc) {
delete this; delete this;
else if (m_refCount < 0) } else if (m_refCount < 0) {
throw std::runtime_error("Internal error: reference count < 0!"); throw std::runtime_error("Internal error: reference count < 0!");
}
} }
virtual std::string toString() const = 0; virtual std::string toString() const = 0;
...@@ -66,7 +67,9 @@ public: ...@@ -66,7 +67,9 @@ public:
/// Construct a reference from a pointer /// Construct a reference from a pointer
explicit ref(T *ptr) : m_ptr(ptr) { explicit ref(T *ptr) : m_ptr(ptr) {
if (m_ptr) ((Object *) m_ptr)->incRef(); if (m_ptr) {
((Object *) m_ptr)->incRef();
}
print_created(this, "from pointer", m_ptr); track_created((ref_tag*) this, "from pointer"); print_created(this, "from pointer", m_ptr); track_created((ref_tag*) this, "from pointer");
...@@ -74,8 +77,9 @@ public: ...@@ -74,8 +77,9 @@ public:
/// Copy constructor /// Copy constructor
ref(const ref &r) : m_ptr(r.m_ptr) { ref(const ref &r) : m_ptr(r.m_ptr) {
if (m_ptr) if (m_ptr) {
((Object *) m_ptr)->incRef(); ((Object *) m_ptr)->incRef();
}
print_copy_created(this, "with pointer", m_ptr); track_copy_created((ref_tag*) this); print_copy_created(this, "with pointer", m_ptr); track_copy_created((ref_tag*) this);
} }
...@@ -89,8 +93,9 @@ public: ...@@ -89,8 +93,9 @@ public:
/// Destroy this reference /// Destroy this reference
~ref() { ~ref() {
if (m_ptr) if (m_ptr) {
((Object *) m_ptr)->decRef(); ((Object *) m_ptr)->decRef();
}
print_destroyed(this); track_destroyed((ref_tag*) this); print_destroyed(this); track_destroyed((ref_tag*) this);
} }
...@@ -99,10 +104,12 @@ public: ...@@ -99,10 +104,12 @@ public:
ref &operator=(ref &&r) noexcept { ref &operator=(ref &&r) noexcept {
print_move_assigned(this, "pointer", r.m_ptr); track_move_assigned((ref_tag*) this); print_move_assigned(this, "pointer", r.m_ptr); track_move_assigned((ref_tag*) this);
if (*this == r) if (*this == r) {
return *this; return *this;
if (m_ptr) }
if (m_ptr) {
((Object *) m_ptr)->decRef(); ((Object *) m_ptr)->decRef();
}
m_ptr = r.m_ptr; m_ptr = r.m_ptr;
r.m_ptr = nullptr; r.m_ptr = nullptr;
return *this; return *this;
...@@ -116,13 +123,16 @@ public: ...@@ -116,13 +123,16 @@ public:
print_copy_assigned(this, "pointer", r.m_ptr); print_copy_assigned(this, "pointer", r.m_ptr);
track_copy_assigned((ref_tag *) this); track_copy_assigned((ref_tag *) this);
if (m_ptr == r.m_ptr) if (m_ptr == r.m_ptr) {
return *this; return *this;
if (m_ptr) }
if (m_ptr) {
((Object *) m_ptr)->decRef(); ((Object *) m_ptr)->decRef();
}
m_ptr = r.m_ptr; m_ptr = r.m_ptr;
if (m_ptr) if (m_ptr) {
((Object *) m_ptr)->incRef(); ((Object *) m_ptr)->incRef();
}
return *this; return *this;
} }
...@@ -130,13 +140,16 @@ public: ...@@ -130,13 +140,16 @@ public:
ref& operator=(T *ptr) { ref& operator=(T *ptr) {
print_values(this, "assigned pointer"); track_values((ref_tag*) this, "assigned pointer"); print_values(this, "assigned pointer"); track_values((ref_tag*) this, "assigned pointer");
if (m_ptr == ptr) if (m_ptr == ptr) {
return *this; return *this;
if (m_ptr) }
if (m_ptr) {
((Object *) m_ptr)->decRef(); ((Object *) m_ptr)->decRef();
}
m_ptr = ptr; m_ptr = ptr;
if (m_ptr) if (m_ptr) {
((Object *) m_ptr)->incRef(); ((Object *) m_ptr)->incRef();
}
return *this; return *this;
} }
......
...@@ -39,7 +39,9 @@ PYBIND11_MODULE(pybind11_cross_module_tests, m) { ...@@ -39,7 +39,9 @@ PYBIND11_MODULE(pybind11_cross_module_tests, m) {
m.def("throw_local_simple_error", []() { throw LocalSimpleException("external mod"); }); m.def("throw_local_simple_error", []() { throw LocalSimpleException("external mod"); });
py::register_exception_translator([](std::exception_ptr p) { py::register_exception_translator([](std::exception_ptr p) {
try { try {
if (p) std::rethrow_exception(p); if (p) {
std::rethrow_exception(p);
}
} catch (const shared_exception &e) { } catch (const shared_exception &e) {
PyErr_SetString(PyExc_KeyError, e.what()); PyErr_SetString(PyExc_KeyError, e.what());
} }
......
...@@ -86,6 +86,7 @@ PYBIND11_MODULE(pybind11_tests, m) { ...@@ -86,6 +86,7 @@ PYBIND11_MODULE(pybind11_tests, m) {
.def(py::init<int>()) .def(py::init<int>())
.def("__repr__", [](const IncType& u) { return "IncType({})"_s.format(u.value()); }); .def("__repr__", [](const IncType& u) { return "IncType({})"_s.format(u.value()); });
for (const auto &initializer : initializers()) for (const auto &initializer : initializers()) {
initializer(m); initializer(m);
}
} }
...@@ -85,8 +85,9 @@ TEST_SUBMODULE(buffers, m) { ...@@ -85,8 +85,9 @@ TEST_SUBMODULE(buffers, m) {
/// Construct from a buffer /// Construct from a buffer
.def(py::init([](const py::buffer &b) { .def(py::init([](const py::buffer &b) {
py::buffer_info info = b.request(); py::buffer_info info = b.request();
if (info.format != py::format_descriptor<float>::format() || info.ndim != 2) if (info.format != py::format_descriptor<float>::format() || info.ndim != 2) {
throw std::runtime_error("Incompatible buffer format!"); throw std::runtime_error("Incompatible buffer format!");
}
auto v = new Matrix(info.shape[0], info.shape[1]); auto v = new Matrix(info.shape[0], info.shape[1]);
memcpy(v->data(), info.ptr, sizeof(float) * (size_t) (v->rows() * v->cols())); memcpy(v->data(), info.ptr, sizeof(float) * (size_t) (v->rows() * v->cols()));
...@@ -99,14 +100,16 @@ TEST_SUBMODULE(buffers, m) { ...@@ -99,14 +100,16 @@ TEST_SUBMODULE(buffers, m) {
/// Bare bones interface /// Bare bones interface
.def("__getitem__", .def("__getitem__",
[](const Matrix &m, std::pair<py::ssize_t, py::ssize_t> i) { [](const Matrix &m, std::pair<py::ssize_t, py::ssize_t> i) {
if (i.first >= m.rows() || i.second >= m.cols()) if (i.first >= m.rows() || i.second >= m.cols()) {
throw py::index_error(); throw py::index_error();
}
return m(i.first, i.second); return m(i.first, i.second);
}) })
.def("__setitem__", .def("__setitem__",
[](Matrix &m, std::pair<py::ssize_t, py::ssize_t> i, float v) { [](Matrix &m, std::pair<py::ssize_t, py::ssize_t> i, float v) {
if (i.first >= m.rows() || i.second >= m.cols()) if (i.first >= m.rows() || i.second >= m.cols()) {
throw py::index_error(); throw py::index_error();
}
m(i.first, i.second) = v; m(i.first, i.second) = v;
}) })
/// Provide buffer access /// Provide buffer access
......
...@@ -93,8 +93,11 @@ TEST_SUBMODULE(builtin_casters, m) { ...@@ -93,8 +93,11 @@ TEST_SUBMODULE(builtin_casters, m) {
#if PY_MAJOR_VERSION >= 3 #if PY_MAJOR_VERSION >= 3
// Under Python 2.7, invalid unicode UTF-32 characters don't appear to trigger UnicodeDecodeError // Under Python 2.7, invalid unicode UTF-32 characters don't appear to trigger UnicodeDecodeError
m.def("bad_utf32_string", [=]() { return std::u32string({ a32, char32_t(0xd800), z32 }); }); m.def("bad_utf32_string", [=]() { return std::u32string({ a32, char32_t(0xd800), z32 }); });
if (PYBIND11_SILENCE_MSVC_C4127(sizeof(wchar_t) == 2)) if (PYBIND11_SILENCE_MSVC_C4127(sizeof(wchar_t) == 2)) {
m.def("bad_wchar_string", [=]() { return std::wstring({ wchar_t(0x61), wchar_t(0xd800) }); }); m.def("bad_wchar_string", [=]() {
return std::wstring({wchar_t(0x61), wchar_t(0xd800)});
});
}
#endif #endif
m.def("u8_Z", []() -> char { return 'Z'; }); m.def("u8_Z", []() -> char { return 'Z'; });
m.def("u8_eacute", []() -> char { return '\xe9'; }); m.def("u8_eacute", []() -> char { return '\xe9'; });
...@@ -133,9 +136,21 @@ TEST_SUBMODULE(builtin_casters, m) { ...@@ -133,9 +136,21 @@ TEST_SUBMODULE(builtin_casters, m) {
m.def("string_view_print", [](std::string_view s) { py::print(s, s.size()); }); m.def("string_view_print", [](std::string_view s) { py::print(s, s.size()); });
m.def("string_view16_print", [](std::u16string_view s) { py::print(s, s.size()); }); m.def("string_view16_print", [](std::u16string_view s) { py::print(s, s.size()); });
m.def("string_view32_print", [](std::u32string_view s) { py::print(s, s.size()); }); m.def("string_view32_print", [](std::u32string_view s) { py::print(s, s.size()); });
m.def("string_view_chars", [](std::string_view s) { py::list l; for (auto c : s) l.append((std::uint8_t) c); return l; }); m.def("string_view_chars", [](std::string_view s) { py::list l;
m.def("string_view16_chars", [](std::u16string_view s) { py::list l; for (auto c : s) l.append((int) c); return l; }); for (auto c : s) {
m.def("string_view32_chars", [](std::u32string_view s) { py::list l; for (auto c : s) l.append((int) c); return l; }); l.append((std::uint8_t) c);
}
return l; });
m.def("string_view16_chars", [](std::u16string_view s) { py::list l;
for (auto c : s) {
l.append((int) c);
}
return l; });
m.def("string_view32_chars", [](std::u32string_view s) { py::list l;
for (auto c : s) {
l.append((int) c);
}
return l; });
m.def("string_view_return", []() { return std::string_view((const char*)u8"utf8 secret \U0001f382"); }); m.def("string_view_return", []() { return std::string_view((const char*)u8"utf8 secret \U0001f382"); });
m.def("string_view16_return", []() { return std::u16string_view(u"utf16 secret \U0001f382"); }); m.def("string_view16_return", []() { return std::u16string_view(u"utf16 secret \U0001f382"); });
m.def("string_view32_return", []() { return std::u32string_view(U"utf32 secret \U0001f382"); }); m.def("string_view32_return", []() { return std::u32string_view(U"utf32 secret \U0001f382"); });
......
...@@ -95,8 +95,9 @@ TEST_SUBMODULE(call_policies, m) { ...@@ -95,8 +95,9 @@ TEST_SUBMODULE(call_policies, m) {
// but it's unclear how to test it without `PyGILState_GetThisThreadState`. // but it's unclear how to test it without `PyGILState_GetThisThreadState`.
auto report_gil_status = []() { auto report_gil_status = []() {
auto is_gil_held = false; auto is_gil_held = false;
if (auto tstate = py::detail::get_thread_state_unchecked()) if (auto tstate = py::detail::get_thread_state_unchecked()) {
is_gil_held = (tstate == PyGILState_GetThisThreadState()); is_gil_held = (tstate == PyGILState_GetThisThreadState());
}
return is_gil_held ? "GIL held" : "GIL released"; return is_gil_held ? "GIL held" : "GIL released";
}; };
......
...@@ -136,11 +136,16 @@ TEST_SUBMODULE(callbacks, m) { ...@@ -136,11 +136,16 @@ TEST_SUBMODULE(callbacks, m) {
m.def("dummy_function_overloaded", [](int i, int j) { return i + j; }); m.def("dummy_function_overloaded", [](int i, int j) { return i + j; });
m.def("dummy_function_overloaded", &dummy_function); m.def("dummy_function_overloaded", &dummy_function);
m.def("dummy_function2", [](int i, int j) { return i + j; }); m.def("dummy_function2", [](int i, int j) { return i + j; });
m.def("roundtrip", [](std::function<int(int)> f, bool expect_none = false) { m.def(
if (expect_none && f) "roundtrip",
throw std::runtime_error("Expected None to be converted to empty std::function"); [](std::function<int(int)> f, bool expect_none = false) {
return f; if (expect_none && f) {
}, py::arg("f"), py::arg("expect_none")=false); throw std::runtime_error("Expected None to be converted to empty std::function");
}
return f;
},
py::arg("f"),
py::arg("expect_none") = false);
m.def("test_dummy_function", [](const std::function<int(int)> &f) -> std::string { m.def("test_dummy_function", [](const std::function<int(int)> &f) -> std::string {
using fn_type = int (*)(int); using fn_type = int (*)(int);
auto result = f.target<fn_type>(); auto result = f.target<fn_type>();
...@@ -215,8 +220,9 @@ TEST_SUBMODULE(callbacks, m) { ...@@ -215,8 +220,9 @@ TEST_SUBMODULE(callbacks, m) {
}; };
// spawn worker threads // spawn worker threads
for (auto i : work) for (auto i : work) {
start_f(py::cast<int>(i)); start_f(py::cast<int>(i));
}
}); });
m.def("callback_num_times", [](const py::function &f, std::size_t num) { m.def("callback_num_times", [](const py::function &f, std::size_t num) {
......
...@@ -139,9 +139,13 @@ TEST_SUBMODULE(class_, m) { ...@@ -139,9 +139,13 @@ TEST_SUBMODULE(class_, m) {
m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); }); m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); });
m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); }); m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); });
m.def("return_class_n", [](int n) -> BaseClass* { m.def("return_class_n", [](int n) -> BaseClass * {
if (n == 1) return new DerivedClass1(); if (n == 1) {
if (n == 2) return new DerivedClass2(); return new DerivedClass1();
}
if (n == 2) {
return new DerivedClass2();
}
return new BaseClass(); return new BaseClass();
}); });
m.def("return_none", []() -> BaseClass* { return nullptr; }); m.def("return_none", []() -> BaseClass* { return nullptr; });
...@@ -167,8 +171,9 @@ TEST_SUBMODULE(class_, m) { ...@@ -167,8 +171,9 @@ TEST_SUBMODULE(class_, m) {
// See https://github.com/pybind/pybind11/issues/2486 // See https://github.com/pybind/pybind11/issues/2486
// if (category == 2) // if (category == 2)
// return py::type::of<int>(); // return py::type::of<int>();
if (category == 1) if (category == 1) {
return py::type::of<DerivedClass1>(); return py::type::of<DerivedClass1>();
}
return py::type::of<Invalid>(); return py::type::of<Invalid>();
}); });
......
...@@ -104,7 +104,9 @@ public: ...@@ -104,7 +104,9 @@ public:
bool load(handle src, bool) { value = CopyOnlyInt(src.cast<int>()); return true; } bool load(handle src, bool) { value = CopyOnlyInt(src.cast<int>()); return true; }
static handle cast(const CopyOnlyInt &m, return_value_policy r, handle p) { return pybind11::cast(m.value, r, p); } static handle cast(const CopyOnlyInt &m, return_value_policy r, handle p) { return pybind11::cast(m.value, r, p); }
static handle cast(const CopyOnlyInt *src, return_value_policy policy, handle parent) { static handle cast(const CopyOnlyInt *src, return_value_policy policy, handle parent) {
if (!src) return none().release(); if (!src) {
return none().release();
}
return cast(*src, policy, parent); return cast(*src, policy, parent);
} }
explicit operator CopyOnlyInt *() { return &value; } explicit operator CopyOnlyInt *() { return &value; }
...@@ -203,8 +205,9 @@ TEST_SUBMODULE(copy_move_policies, m) { ...@@ -203,8 +205,9 @@ TEST_SUBMODULE(copy_move_policies, m) {
private: private:
void *operator new(size_t bytes) { void *operator new(size_t bytes) {
void *ptr = std::malloc(bytes); void *ptr = std::malloc(bytes);
if (ptr) if (ptr) {
return ptr; return ptr;
}
throw std::bad_alloc{}; throw std::bad_alloc{};
} }
}; };
......
...@@ -28,8 +28,11 @@ using MatrixXdR = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::R ...@@ -28,8 +28,11 @@ using MatrixXdR = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::R
// Sets/resets a testing reference matrix to have values of 10*r + c, where r and c are the // Sets/resets a testing reference matrix to have values of 10*r + c, where r and c are the
// (1-based) row/column number. // (1-based) row/column number.
template <typename M> void reset_ref(M &x) { template <typename M> void reset_ref(M &x) {
for (int i = 0; i < x.rows(); i++) for (int j = 0; j < x.cols(); j++) for (int i = 0; i < x.rows(); i++) {
x(i, j) = 11 + 10*i + j; for (int j = 0; j < x.cols(); j++) {
x(i, j) = 11 + 10 * i + j;
}
}
} }
// Returns a static, column-major matrix // Returns a static, column-major matrix
...@@ -63,9 +66,11 @@ double get_elem(const Eigen::Ref<const Eigen::MatrixXd> &m) { return m(2, 1); }; ...@@ -63,9 +66,11 @@ double get_elem(const Eigen::Ref<const Eigen::MatrixXd> &m) { return m(2, 1); };
// reference is referencing rows/columns correctly). // reference is referencing rows/columns correctly).
template <typename MatrixArgType> Eigen::MatrixXd adjust_matrix(MatrixArgType m) { template <typename MatrixArgType> Eigen::MatrixXd adjust_matrix(MatrixArgType m) {
Eigen::MatrixXd ret(m); Eigen::MatrixXd ret(m);
for (int c = 0; c < m.cols(); c++) for (int c = 0; c < m.cols(); c++) {
for (int r = 0; r < m.rows(); r++) for (int r = 0; r < m.rows(); r++) {
ret(r, c) += 10*r + 100*c; // NOLINT(clang-analyzer-core.uninitialized.Assign) ret(r, c) += 10 * r + 100 * c; // NOLINT(clang-analyzer-core.uninitialized.Assign)
}
}
return ret; return ret;
} }
...@@ -225,7 +230,9 @@ TEST_SUBMODULE(eigen, m) { ...@@ -225,7 +230,9 @@ TEST_SUBMODULE(eigen, m) {
// Returns a DiagonalMatrix with diagonal (1,2,3,...) // Returns a DiagonalMatrix with diagonal (1,2,3,...)
m.def("incr_diag", [](int k) { m.def("incr_diag", [](int k) {
Eigen::DiagonalMatrix<int, Eigen::Dynamic> m(k); Eigen::DiagonalMatrix<int, Eigen::Dynamic> m(k);
for (int i = 0; i < k; i++) m.diagonal()[i] = i+1; for (int i = 0; i < k; i++) {
m.diagonal()[i] = i + 1;
}
return m; return m;
}); });
...@@ -320,8 +327,9 @@ TEST_SUBMODULE(eigen, m) { ...@@ -320,8 +327,9 @@ TEST_SUBMODULE(eigen, m) {
"matrix_multiply", "matrix_multiply",
[](const py::EigenDRef<const Eigen::MatrixXd> &A, [](const py::EigenDRef<const Eigen::MatrixXd> &A,
const py::EigenDRef<const Eigen::MatrixXd> &B) -> Eigen::MatrixXd { const py::EigenDRef<const Eigen::MatrixXd> &B) -> Eigen::MatrixXd {
if (A.cols() != B.rows()) if (A.cols() != B.rows()) {
throw std::domain_error("Nonconformable matrices!"); throw std::domain_error("Nonconformable matrices!");
}
return A * B; return A * B;
}, },
py::arg("A"), py::arg("A"),
......
...@@ -307,7 +307,11 @@ TEST_CASE("Threads") { ...@@ -307,7 +307,11 @@ TEST_CASE("Threads") {
struct scope_exit { struct scope_exit {
std::function<void()> f_; std::function<void()> f_;
explicit scope_exit(std::function<void()> f) noexcept : f_(std::move(f)) {} explicit scope_exit(std::function<void()> f) noexcept : f_(std::move(f)) {}
~scope_exit() { if (f_) f_(); } ~scope_exit() {
if (f_) {
f_();
}
}
}; };
TEST_CASE("Reload module from file") { TEST_CASE("Reload module from file") {
......
...@@ -93,8 +93,9 @@ TEST_SUBMODULE(eval_, m) { ...@@ -93,8 +93,9 @@ TEST_SUBMODULE(eval_, m) {
// test_eval_empty_globals // test_eval_empty_globals
m.def("eval_empty_globals", [](py::object global) { m.def("eval_empty_globals", [](py::object global) {
if (global.is_none()) if (global.is_none()) {
global = py::dict(); global = py::dict();
}
auto int_class = py::eval("isinstance(42, int)", global); auto int_class = py::eval("isinstance(42, int)", global);
return global; return global;
}); });
......
...@@ -116,7 +116,9 @@ TEST_SUBMODULE(exceptions, m) { ...@@ -116,7 +116,9 @@ TEST_SUBMODULE(exceptions, m) {
static py::exception<MyException> ex(m, "MyException"); static py::exception<MyException> ex(m, "MyException");
py::register_exception_translator([](std::exception_ptr p) { py::register_exception_translator([](std::exception_ptr p) {
try { try {
if (p) std::rethrow_exception(p); if (p) {
std::rethrow_exception(p);
}
} catch (const MyException &e) { } catch (const MyException &e) {
// Set MyException as the active python error // Set MyException as the active python error
ex(e.what()); ex(e.what());
...@@ -128,7 +130,9 @@ TEST_SUBMODULE(exceptions, m) { ...@@ -128,7 +130,9 @@ TEST_SUBMODULE(exceptions, m) {
// never by visible from Python // never by visible from Python
py::register_exception_translator([](std::exception_ptr p) { py::register_exception_translator([](std::exception_ptr p) {
try { try {
if (p) std::rethrow_exception(p); if (p) {
std::rethrow_exception(p);
}
} catch (const MyException2 &e) { } catch (const MyException2 &e) {
// Translate this exception to a standard RuntimeError // Translate this exception to a standard RuntimeError
PyErr_SetString(PyExc_RuntimeError, e.what()); PyErr_SetString(PyExc_RuntimeError, e.what());
...@@ -140,7 +144,9 @@ TEST_SUBMODULE(exceptions, m) { ...@@ -140,7 +144,9 @@ TEST_SUBMODULE(exceptions, m) {
// translator for MyException by throwing a new exception // translator for MyException by throwing a new exception
py::register_exception_translator([](std::exception_ptr p) { py::register_exception_translator([](std::exception_ptr p) {
try { try {
if (p) std::rethrow_exception(p); if (p) {
std::rethrow_exception(p);
}
} catch (const MyException4 &e) { } catch (const MyException4 &e) {
throw MyException(e.what()); throw MyException(e.what());
} }
...@@ -181,7 +187,9 @@ TEST_SUBMODULE(exceptions, m) { ...@@ -181,7 +187,9 @@ TEST_SUBMODULE(exceptions, m) {
py::object o = foo["bar"]; py::object o = foo["bar"];
} }
catch (py::error_already_set& ex) { catch (py::error_already_set& ex) {
if (!ex.matches(PyExc_KeyError)) throw; if (!ex.matches(PyExc_KeyError)) {
throw;
}
return true; return true;
} }
return false; return false;
...@@ -193,7 +201,9 @@ TEST_SUBMODULE(exceptions, m) { ...@@ -193,7 +201,9 @@ TEST_SUBMODULE(exceptions, m) {
py::object o = foo["bar"]; py::object o = foo["bar"];
} }
catch (py::error_already_set &ex) { catch (py::error_already_set &ex) {
if (!ex.matches(PyExc_Exception)) throw; if (!ex.matches(PyExc_Exception)) {
throw;
}
return true; return true;
} }
return false; return false;
...@@ -204,15 +214,18 @@ TEST_SUBMODULE(exceptions, m) { ...@@ -204,15 +214,18 @@ TEST_SUBMODULE(exceptions, m) {
py::module_::import("nonexistent"); py::module_::import("nonexistent");
} }
catch (py::error_already_set &ex) { catch (py::error_already_set &ex) {
if (!ex.matches(PyExc_ImportError)) throw; if (!ex.matches(PyExc_ImportError)) {
throw;
}
return true; return true;
} }
return false; return false;
}); });
m.def("throw_already_set", [](bool err) { m.def("throw_already_set", [](bool err) {
if (err) if (err) {
PyErr_SetString(PyExc_ValueError, "foo"); PyErr_SetString(PyExc_ValueError, "foo");
}
try { try {
throw py::error_already_set(); throw py::error_already_set();
} catch (const std::runtime_error& e) { } catch (const std::runtime_error& e) {
...@@ -224,8 +237,9 @@ TEST_SUBMODULE(exceptions, m) { ...@@ -224,8 +237,9 @@ TEST_SUBMODULE(exceptions, m) {
} }
} }
PyErr_Clear(); PyErr_Clear();
if (err) if (err) {
PyErr_SetString(PyExc_ValueError, "foo"); PyErr_SetString(PyExc_ValueError, "foo");
}
throw py::error_already_set(); throw py::error_already_set();
}); });
...@@ -252,10 +266,11 @@ TEST_SUBMODULE(exceptions, m) { ...@@ -252,10 +266,11 @@ TEST_SUBMODULE(exceptions, m) {
try { try {
f(*args); f(*args);
} catch (py::error_already_set &ex) { } catch (py::error_already_set &ex) {
if (ex.matches(exc_type)) if (ex.matches(exc_type)) {
py::print(ex.what()); py::print(ex.what());
else } else {
throw; throw;
}
} }
}); });
......
...@@ -22,8 +22,9 @@ ...@@ -22,8 +22,9 @@
void noisy_function(const std::string &msg, bool flush) { void noisy_function(const std::string &msg, bool flush) {
std::cout << msg; std::cout << msg;
if (flush) if (flush) {
std::cout << std::flush; std::cout << std::flush;
}
} }
void noisy_funct_dual(const std::string &msg, const std::string &emsg) { void noisy_funct_dual(const std::string &msg, const std::string &emsg) {
......
...@@ -26,8 +26,9 @@ TEST_SUBMODULE(kwargs_and_defaults, m) { ...@@ -26,8 +26,9 @@ TEST_SUBMODULE(kwargs_and_defaults, m) {
std::vector<int> list{{13, 17}}; std::vector<int> list{{13, 17}};
m.def("kw_func4", [](const std::vector<int> &entries) { m.def("kw_func4", [](const std::vector<int> &entries) {
std::string ret = "{"; std::string ret = "{";
for (int i : entries) for (int i : entries) {
ret += std::to_string(i) + " "; ret += std::to_string(i) + " ";
}
ret.back() = '}'; ret.back() = '}';
return ret; return ret;
}, py::arg("myList") = list); }, py::arg("myList") = list);
...@@ -89,18 +90,20 @@ TEST_SUBMODULE(kwargs_and_defaults, m) { ...@@ -89,18 +90,20 @@ TEST_SUBMODULE(kwargs_and_defaults, m) {
m.def("args_refcount", [](py::args a) { m.def("args_refcount", [](py::args a) {
GC_IF_NEEDED; GC_IF_NEEDED;
py::tuple t(a.size()); py::tuple t(a.size());
for (size_t i = 0; i < a.size(); i++) for (size_t i = 0; i < a.size(); i++) {
// Use raw Python API here to avoid an extra, intermediate incref on the tuple item: // Use raw Python API here to avoid an extra, intermediate incref on the tuple item:
t[i] = (int) Py_REFCNT(PyTuple_GET_ITEM(a.ptr(), static_cast<py::ssize_t>(i))); t[i] = (int) Py_REFCNT(PyTuple_GET_ITEM(a.ptr(), static_cast<py::ssize_t>(i)));
}
return t; return t;
}); });
m.def("mixed_args_refcount", [](const py::object &o, py::args a) { m.def("mixed_args_refcount", [](const py::object &o, py::args a) {
GC_IF_NEEDED; GC_IF_NEEDED;
py::tuple t(a.size() + 1); py::tuple t(a.size() + 1);
t[0] = o.ref_count(); t[0] = o.ref_count();
for (size_t i = 0; i < a.size(); i++) for (size_t i = 0; i < a.size(); i++) {
// Use raw Python API here to avoid an extra, intermediate incref on the tuple item: // Use raw Python API here to avoid an extra, intermediate incref on the tuple item:
t[i + 1] = (int) Py_REFCNT(PyTuple_GET_ITEM(a.ptr(), static_cast<py::ssize_t>(i))); t[i + 1] = (int) Py_REFCNT(PyTuple_GET_ITEM(a.ptr(), static_cast<py::ssize_t>(i)));
}
return t; return t;
}); });
......
...@@ -47,8 +47,9 @@ TEST_SUBMODULE(local_bindings, m) { ...@@ -47,8 +47,9 @@ TEST_SUBMODULE(local_bindings, m) {
auto main = py::module_::import("pybind11_tests"); auto main = py::module_::import("pybind11_tests");
if (py::hasattr(main, "class_")) { if (py::hasattr(main, "class_")) {
bind_local<LocalExternal, 7>(m, "LocalExternal", py::module_local()); bind_local<LocalExternal, 7>(m, "LocalExternal", py::module_local());
} else {
throw std::runtime_error("test_class not enabled");
} }
else throw std::runtime_error("test_class not enabled");
}); });
// test_stl_bind_local // test_stl_bind_local
......
...@@ -90,15 +90,17 @@ template<typename... Ix> arr data_t(const arr_t& a, Ix... index) { ...@@ -90,15 +90,17 @@ template<typename... Ix> arr data_t(const arr_t& a, Ix... index) {
template<typename... Ix> arr& mutate_data(arr& a, Ix... index) { template<typename... Ix> arr& mutate_data(arr& a, Ix... index) {
auto ptr = (uint8_t *) a.mutable_data(index...); auto ptr = (uint8_t *) a.mutable_data(index...);
for (py::ssize_t i = 0; i < a.nbytes() - a.offset_at(index...); i++) for (py::ssize_t i = 0; i < a.nbytes() - a.offset_at(index...); i++) {
ptr[i] = (uint8_t) (ptr[i] * 2); ptr[i] = (uint8_t) (ptr[i] * 2);
}
return a; return a;
} }
template<typename... Ix> arr_t& mutate_data_t(arr_t& a, Ix... index) { template<typename... Ix> arr_t& mutate_data_t(arr_t& a, Ix... index) {
auto ptr = a.mutable_data(index...); auto ptr = a.mutable_data(index...);
for (py::ssize_t i = 0; i < a.size() - a.index_at(index...); i++) for (py::ssize_t i = 0; i < a.size() - a.index_at(index...); i++) {
ptr[i]++; ptr[i]++;
}
return a; return a;
} }
...@@ -116,7 +118,9 @@ template<typename... Ix> arr_t& mutate_at_t(arr_t& a, Ix... idx) { a.mutable_at( ...@@ -116,7 +118,9 @@ template<typename... Ix> arr_t& mutate_at_t(arr_t& a, Ix... idx) { a.mutable_at(
sm.def(#name, [](type a, int i, int j, int k) { return name(a, i, j, k); }); sm.def(#name, [](type a, int i, int j, int k) { return name(a, i, j, k); });
template <typename T, typename T2> py::handle auxiliaries(T &&r, T2 &&r2) { template <typename T, typename T2> py::handle auxiliaries(T &&r, T2 &&r2) {
if (r.ndim() != 2) throw std::domain_error("error: ndim != 2"); if (r.ndim() != 2) {
throw std::domain_error("error: ndim != 2");
}
py::list l; py::list l;
l.append(*r.data(0, 0)); l.append(*r.data(0, 0));
l.append(*r2.mutable_data(0, 0)); l.append(*r2.mutable_data(0, 0));
...@@ -292,34 +296,43 @@ TEST_SUBMODULE(numpy_array, sm) { ...@@ -292,34 +296,43 @@ TEST_SUBMODULE(numpy_array, sm) {
// test_array_unchecked_fixed_dims // test_array_unchecked_fixed_dims
sm.def("proxy_add2", [](py::array_t<double> a, double v) { sm.def("proxy_add2", [](py::array_t<double> a, double v) {
auto r = a.mutable_unchecked<2>(); auto r = a.mutable_unchecked<2>();
for (py::ssize_t i = 0; i < r.shape(0); i++) for (py::ssize_t i = 0; i < r.shape(0); i++) {
for (py::ssize_t j = 0; j < r.shape(1); j++) for (py::ssize_t j = 0; j < r.shape(1); j++) {
r(i, j) += v; r(i, j) += v;
}
}
}, py::arg{}.noconvert(), py::arg()); }, py::arg{}.noconvert(), py::arg());
sm.def("proxy_init3", [](double start) { sm.def("proxy_init3", [](double start) {
py::array_t<double, py::array::c_style> a({ 3, 3, 3 }); py::array_t<double, py::array::c_style> a({ 3, 3, 3 });
auto r = a.mutable_unchecked<3>(); auto r = a.mutable_unchecked<3>();
for (py::ssize_t i = 0; i < r.shape(0); i++) for (py::ssize_t i = 0; i < r.shape(0); i++) {
for (py::ssize_t j = 0; j < r.shape(1); j++) for (py::ssize_t j = 0; j < r.shape(1); j++) {
for (py::ssize_t k = 0; k < r.shape(2); k++) for (py::ssize_t k = 0; k < r.shape(2); k++) {
r(i, j, k) = start++; r(i, j, k) = start++;
}
}
}
return a; return a;
}); });
sm.def("proxy_init3F", [](double start) { sm.def("proxy_init3F", [](double start) {
py::array_t<double, py::array::f_style> a({ 3, 3, 3 }); py::array_t<double, py::array::f_style> a({ 3, 3, 3 });
auto r = a.mutable_unchecked<3>(); auto r = a.mutable_unchecked<3>();
for (py::ssize_t k = 0; k < r.shape(2); k++) for (py::ssize_t k = 0; k < r.shape(2); k++) {
for (py::ssize_t j = 0; j < r.shape(1); j++) for (py::ssize_t j = 0; j < r.shape(1); j++) {
for (py::ssize_t i = 0; i < r.shape(0); i++) for (py::ssize_t i = 0; i < r.shape(0); i++) {
r(i, j, k) = start++; r(i, j, k) = start++;
}
}
}
return a; return a;
}); });
sm.def("proxy_squared_L2_norm", [](const py::array_t<double> &a) { sm.def("proxy_squared_L2_norm", [](const py::array_t<double> &a) {
auto r = a.unchecked<1>(); auto r = a.unchecked<1>();
double sumsq = 0; double sumsq = 0;
for (py::ssize_t i = 0; i < r.shape(0); i++) for (py::ssize_t i = 0; i < r.shape(0); i++) {
sumsq += r[i] * r(i); // Either notation works for a 1D array sumsq += r[i] * r(i); // Either notation works for a 1D array
}
return sumsq; return sumsq;
}); });
...@@ -345,19 +358,28 @@ TEST_SUBMODULE(numpy_array, sm) { ...@@ -345,19 +358,28 @@ TEST_SUBMODULE(numpy_array, sm) {
// Same as the above, but without a compile-time dimensions specification: // Same as the above, but without a compile-time dimensions specification:
sm.def("proxy_add2_dyn", [](py::array_t<double> a, double v) { sm.def("proxy_add2_dyn", [](py::array_t<double> a, double v) {
auto r = a.mutable_unchecked(); auto r = a.mutable_unchecked();
if (r.ndim() != 2) throw std::domain_error("error: ndim != 2"); if (r.ndim() != 2) {
for (py::ssize_t i = 0; i < r.shape(0); i++) throw std::domain_error("error: ndim != 2");
for (py::ssize_t j = 0; j < r.shape(1); j++) }
for (py::ssize_t i = 0; i < r.shape(0); i++) {
for (py::ssize_t j = 0; j < r.shape(1); j++) {
r(i, j) += v; r(i, j) += v;
}
}
}, py::arg{}.noconvert(), py::arg()); }, py::arg{}.noconvert(), py::arg());
sm.def("proxy_init3_dyn", [](double start) { sm.def("proxy_init3_dyn", [](double start) {
py::array_t<double, py::array::c_style> a({ 3, 3, 3 }); py::array_t<double, py::array::c_style> a({ 3, 3, 3 });
auto r = a.mutable_unchecked(); auto r = a.mutable_unchecked();
if (r.ndim() != 3) throw std::domain_error("error: ndim != 3"); if (r.ndim() != 3) {
for (py::ssize_t i = 0; i < r.shape(0); i++) throw std::domain_error("error: ndim != 3");
for (py::ssize_t j = 0; j < r.shape(1); j++) }
for (py::ssize_t k = 0; k < r.shape(2); k++) for (py::ssize_t i = 0; i < r.shape(0); i++) {
r(i, j, k) = start++; for (py::ssize_t j = 0; j < r.shape(1); j++) {
for (py::ssize_t k = 0; k < r.shape(2); k++) {
r(i, j, k) = start++;
}
}
}
return a; return a;
}); });
sm.def("proxy_auxiliaries2_dyn", [](py::array_t<double> a) { sm.def("proxy_auxiliaries2_dyn", [](py::array_t<double> a) {
...@@ -386,8 +408,10 @@ TEST_SUBMODULE(numpy_array, sm) { ...@@ -386,8 +408,10 @@ TEST_SUBMODULE(numpy_array, sm) {
// reshape array to 2D without changing size // reshape array to 2D without changing size
sm.def("array_reshape2", [](py::array_t<double> a) { sm.def("array_reshape2", [](py::array_t<double> a) {
const auto dim_sz = (py::ssize_t)std::sqrt(a.size()); const auto dim_sz = (py::ssize_t)std::sqrt(a.size());
if (dim_sz * dim_sz != a.size()) if (dim_sz * dim_sz != a.size()) {
throw std::domain_error("array_reshape2: input array total size is not a squared integer"); throw std::domain_error(
"array_reshape2: input array total size is not a squared integer");
}
a.resize({dim_sz, dim_sz}); a.resize({dim_sz, dim_sz});
}); });
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment