This is an automated email from the ASF dual-hosted git repository.
tqchen pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tvm-ffi.git
The following commit(s) were added to refs/heads/main by this push:
new bc6bf774 [Rust] Fix clippy findings (#942)
bc6bf774 is described below
commit bc6bf77478c46c596cae9be611099078ccf85622
Author: Tianqi Chen <[email protected]>
AuthorDate: Fri Nov 6 09:49:31 2026 -0500
[Rust] Fix clippy findings (#942)
Address `cargo clippy --workspace --all-targets` findings with no change
to public signatures or behaviour:
- mechanical fixes: needless return/borrow/conversion, redundant field
names, same-type casts, canonical `partial_cmp`, `div_ceil`, and
`map_err(Into::into)` in `into_typed_fn!` instead of `Ok(x?)`;
- add the missing `# Safety` sections on unsafe traits and functions;
- scope-allow `new_without_default` on `Object` and the sys
`TVMFFIObject`/`TVMFFIAny`, and `result_unit_err` on the
implementor-facing `AnyCompatible::try_cast_from_any_view` and hidden
match-pattern hooks, whose `()` error is deliberate;
- tests: replace PI-like float literals, keep the intentional
`i64::MIN % -1`, `AnyView::clone` and macro-mirroring `(&probe)`
receiver cases under scoped allows.
- CI: run pinned clippy (1.99.1, `-D warnings`) on ubuntu after the
Rust tests, when `rust/` changes.
---
.github/workflows/ci_test.yml | 17 +++++++++
rust/tvm-ffi-sys/src/c_api.rs | 8 +++--
rust/tvm-ffi-sys/src/dlpack.rs | 8 ++---
rust/tvm-ffi/src/any.rs | 4 +--
rust/tvm-ffi/src/collections/shape.rs | 2 +-
rust/tvm-ffi/src/collections/tensor.rs | 26 ++++++++++----
rust/tvm-ffi/src/device.rs | 2 +-
rust/tvm-ffi/src/dtype.rs | 4 +--
rust/tvm-ffi/src/error.rs | 2 +-
rust/tvm-ffi/src/extra/structural_visit.rs | 1 +
rust/tvm-ffi/src/extra/structural_walk.rs | 15 +++-----
rust/tvm-ffi/src/function.rs | 4 +--
rust/tvm-ffi/src/function_internal.rs | 5 ++-
rust/tvm-ffi/src/macros.rs | 38 +++++++++++++++-----
rust/tvm-ffi/src/match_any_internal.rs | 3 ++
rust/tvm-ffi/src/object.rs | 15 ++++++--
rust/tvm-ffi/src/optional.rs | 4 +++
rust/tvm-ffi/src/string.rs | 20 +++++------
rust/tvm-ffi/src/type_traits.rs | 42 ++++++++++++++++------
rust/tvm-ffi/tests/test_any.rs | 19 +++++-----
rust/tvm-ffi/tests/test_array.rs | 2 +-
rust/tvm-ffi/tests/test_big_int.rs | 6 ++--
rust/tvm-ffi/tests/test_function.rs | 2 +-
rust/tvm-ffi/tests/test_list.rs | 6 ++--
rust/tvm-ffi/tests/test_match_any.rs | 2 ++
rust/tvm-ffi/tests/test_match_any_ast_lookup.rs | 2 ++
rust/tvm-ffi/tests/test_rs_object.rs | 4 +--
rust/tvm-ffi/tests/test_structural_mutate.rs | 27 +++++++-------
rust/tvm-ffi/tests/test_structural_visit.rs | 37 +++++++++----------
.../tests/test_structural_visitor_alignment.rs | 2 +-
rust/tvm-ffi/tests/test_tensor.rs | 16 ++++-----
31 files changed, 219 insertions(+), 126 deletions(-)
diff --git a/.github/workflows/ci_test.yml b/.github/workflows/ci_test.yml
index 67712295..f8610f76 100644
--- a/.github/workflows/ci_test.yml
+++ b/.github/workflows/ci_test.yml
@@ -36,6 +36,7 @@ jobs:
cpp_changed: ${{ steps.cpp_files.outputs.changed }}
cpp_files: ${{ steps.cpp_files.outputs.files }}
orcjit_changed: ${{ steps.orcjit_files.outputs.changed }}
+ rust_changed: ${{ steps.rust_files.outputs.changed }}
steps:
- uses: actions/checkout@v5
with:
@@ -63,6 +64,13 @@ jobs:
echo "files=$FILES" >> $GITHUB_OUTPUT
[ -n "$FILES" ] && echo "changed=true" >> $GITHUB_OUTPUT || echo
"changed=false" >> $GITHUB_OUTPUT
+ - name: Detect Rust changes
+ id: rust_files
+ run: |
+ FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD --
\
+ rust/ .github/workflows/ci_test.yml | tr '\n' ' ')
+ [ -n "$FILES" ] && echo "changed=true" >> $GITHUB_OUTPUT || echo
"changed=false" >> $GITHUB_OUTPUT
+
lint:
needs: [prepare]
runs-on: ubuntu-latest
@@ -209,6 +217,15 @@ jobs:
run: |
cargo test
cargo test -p tvm-ffi --features export-metadata
+ # Pin clippy so new lints arrive with a toolchain bump, not a runner
update.
+ - name: Run rust clippy
+ if: >
+ matrix.os == 'ubuntu-latest' &&
+ (github.event_name != 'pull_request' ||
needs.prepare.outputs.rust_changed == 'true')
+ working-directory: rust
+ run: |
+ rustup toolchain install 1.99.1 --profile minimal --component clippy
+ cargo +1.99.1 clippy --workspace --all-targets -- -D warnings
# Build the Rust stubgen example against the installed package. Its
post-build
# step refreshes the bindings in place, so a diff means the checked-in
file was stale.
diff --git a/rust/tvm-ffi-sys/src/c_api.rs b/rust/tvm-ffi-sys/src/c_api.rs
index c43585ef..199ee58c 100644
--- a/rust/tvm-ffi-sys/src/c_api.rs
+++ b/rust/tvm-ffi-sys/src/c_api.rs
@@ -168,6 +168,7 @@ pub struct TVMFFIObject {
}
impl TVMFFIObject {
+ #[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
combined_ref_count: AtomicU64::new(0),
@@ -217,6 +218,7 @@ pub struct TVMFFIAny {
impl TVMFFIAny {
/// create a new instance of TVMFFIAny that represents None
+ #[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
type_index: TVMFFITypeIndex::kTVMFFINone as i32,
@@ -253,14 +255,16 @@ impl TVMFFIByteArray {
unsafe {
std::str::from_utf8_unchecked(std::slice::from_raw_parts(self.data, self.size))
}
}
/// Unsafe function to create a TVMFFIByteArray from a string
- /// This function is unsafe as it does not check lifetime of the string
- /// the caller must ensure that the string is valid for the lifetime of
the TVMFFIByteArray
///
/// # Arguments
/// * `data` - The string to create the TVMFFIByteArray from.
///
/// # Returns
/// * `TVMFFIByteArray` - The created TVMFFIByteArray.
+ ///
+ /// # Safety
+ /// The result borrows `data` without a lifetime; the caller must keep the
+ /// string alive for as long as the TVMFFIByteArray is used.
pub unsafe fn from_str(data: &str) -> Self {
Self {
data: data.as_ptr(),
diff --git a/rust/tvm-ffi-sys/src/dlpack.rs b/rust/tvm-ffi-sys/src/dlpack.rs
index dcbdd31b..2037b43f 100644
--- a/rust/tvm-ffi-sys/src/dlpack.rs
+++ b/rust/tvm-ffi-sys/src/dlpack.rs
@@ -111,8 +111,8 @@ pub struct DLTensor {
impl DLDevice {
pub fn new(device_type: DLDeviceType, device_id: i32) -> Self {
Self {
- device_type: device_type,
- device_id: device_id,
+ device_type,
+ device_id,
}
}
}
@@ -121,8 +121,8 @@ impl DLDataType {
pub fn new(code: DLDataTypeCode, bits: u8, lanes: u16) -> Self {
Self {
code: code as u8,
- bits: bits,
- lanes: lanes,
+ bits,
+ lanes,
}
}
}
diff --git a/rust/tvm-ffi/src/any.rs b/rust/tvm-ffi/src/any.rs
index 6c6b1dfc..12f34939 100644
--- a/rust/tvm-ffi/src/any.rs
+++ b/rust/tvm-ffi/src/any.rs
@@ -203,9 +203,9 @@ impl<'a, T: AnyCompatible> From<&'a T> for AnyView<'a> {
fn from(value: &'a T) -> Self {
unsafe {
let mut data = TVMFFIAny::new();
- T::copy_to_any_view(&value, &mut data);
+ T::copy_to_any_view(value, &mut data);
Self {
- data: data,
+ data,
_phantom: std::marker::PhantomData,
}
}
diff --git a/rust/tvm-ffi/src/collections/shape.rs
b/rust/tvm-ffi/src/collections/shape.rs
index 7abfb7ff..55b9e715 100644
--- a/rust/tvm-ffi/src/collections/shape.rs
+++ b/rust/tvm-ffi/src/collections/shape.rs
@@ -156,7 +156,7 @@ impl Eq for Shape {}
impl PartialOrd for Shape {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
- self.as_slice().partial_cmp(other.as_slice())
+ Some(self.cmp(other))
}
}
diff --git a/rust/tvm-ffi/src/collections/tensor.rs
b/rust/tvm-ffi/src/collections/tensor.rs
index 01e22cdd..a2cfad7e 100644
--- a/rust/tvm-ffi/src/collections/tensor.rs
+++ b/rust/tvm-ffi/src/collections/tensor.rs
@@ -32,6 +32,11 @@ use tvm_ffi_sys::{TVMFFIEnvTensorAlloc, TVMFFIObjectHandle};
// NDAllocator Trait
//-----------------------------------------------------
/// Trait for n-dimensional array allocators
+///
+/// # Safety
+/// `alloc_data` must return a pointer aligned to `MIN_ALIGN` and valid for
+/// `numel() * item_size()` bytes of the prototype, and `free_data` must
release
+/// exactly what `alloc_data` returned.
pub unsafe trait NDAllocator: 'static {
/// The minimum alignment of the data allocated by the allocator
const MIN_ALIGN: usize;
@@ -41,6 +46,9 @@ pub unsafe trait NDAllocator: 'static {
/// * `tensor` - The DLTensor to allocate data for
///
/// This method should fill in the data pointer of the DLTensor.
+ ///
+ /// # Safety
+ /// `prototype` must have a valid shape and dtype.
unsafe fn alloc_data(&mut self, prototype: &DLTensor) -> *mut
core::ffi::c_void;
/// Free data for the given DLTensor
@@ -49,6 +57,10 @@ pub unsafe trait NDAllocator: 'static {
/// * `tensor` - The DLTensor to free data for
///
/// This method should free the data pointer of the DLTensor.
+ ///
+ /// # Safety
+ /// `tensor.data` must come from `alloc_data` on this allocator with the
same
+ /// shape and dtype, and must not be used afterwards.
unsafe fn free_data(&mut self, tensor: &DLTensor);
}
@@ -73,7 +85,7 @@ impl DLTensorExt for DLTensor {
}
fn item_size(&self) -> usize {
- (self.dtype.bits as usize * self.dtype.lanes as usize + 7) / 8
+ (self.dtype.bits as usize * self.dtype.lanes as usize).div_ceil(8)
}
}
@@ -311,15 +323,15 @@ impl Tensor {
object: Object::new(),
dltensor: DLTensor {
data: std::ptr::null_mut(),
- device: device,
+ device,
ndim: shape.len() as i32,
- dtype: dtype,
+ dtype,
shape: std::ptr::null_mut(),
strides: std::ptr::null_mut(),
byte_offset: 0,
},
},
- alloc: alloc,
+ alloc,
};
unsafe {
let mut obj_arc = ObjectArc::new_with_extra_items(tensor_obj);
@@ -403,9 +415,9 @@ unsafe impl NDAllocator for CPUNDAlloc {
const MIN_ALIGN: usize = 64;
unsafe fn alloc_data(&mut self, prototype: &DLTensor) -> *mut
core::ffi::c_void {
- let numel = prototype.numel() as usize;
+ let numel = prototype.numel();
let item_size = prototype.item_size();
- let size = numel * item_size as usize;
+ let size = numel * item_size;
// A zero-size allocation is undefined behavior; an empty tensor gets
an
// aligned dangling pointer, which `free_data` does not release.
if size == 0 {
@@ -420,7 +432,7 @@ unsafe impl NDAllocator for CPUNDAlloc {
}
unsafe fn free_data(&mut self, tensor: &DLTensor) {
- let numel = tensor.numel() as usize;
+ let numel = tensor.numel();
let item_size = tensor.item_size();
let size = numel * item_size;
if size == 0 {
diff --git a/rust/tvm-ffi/src/device.rs b/rust/tvm-ffi/src/device.rs
index 0885edb5..4a844e8e 100644
--- a/rust/tvm-ffi/src/device.rs
+++ b/rust/tvm-ffi/src/device.rs
@@ -120,7 +120,7 @@ unsafe impl AnyCompatible for DLDevice {
}
unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
- return data.type_index == TypeIndex::kTVMFFIDevice as i32;
+ data.type_index == TypeIndex::kTVMFFIDevice as i32
}
unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
diff --git a/rust/tvm-ffi/src/dtype.rs b/rust/tvm-ffi/src/dtype.rs
index 108a7964..ef7b7d30 100644
--- a/rust/tvm-ffi/src/dtype.rs
+++ b/rust/tvm-ffi/src/dtype.rs
@@ -58,7 +58,7 @@ impl DLDataTypeExt for DLDataType {
fn to_string(&self) -> std::string::String {
unsafe {
let mut ffi_any = TVMFFIAny::new();
- crate::check_safe_call!(TVMFFIDataTypeToString(&*self, &mut
ffi_any)).unwrap();
+ crate::check_safe_call!(TVMFFIDataTypeToString(self, &mut
ffi_any)).unwrap();
let name: crate::string::String =
crate::any::Any::from_raw_ffi_any(ffi_any)
.try_into()
.unwrap();
@@ -126,7 +126,7 @@ unsafe impl AnyCompatible for DLDataType {
/// # Returns
/// `true` if the Any contains a DLDataType, `false` otherwise
unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
- return data.type_index == TypeIndex::kTVMFFIDataType as i32;
+ data.type_index == TypeIndex::kTVMFFIDataType as i32
}
/// Copy a DLDataType from an Any view (after type check)
diff --git a/rust/tvm-ffi/src/error.rs b/rust/tvm-ffi/src/error.rs
index 42c3a053..1cdf41be 100644
--- a/rust/tvm-ffi/src/error.rs
+++ b/rust/tvm-ffi/src/error.rs
@@ -272,7 +272,7 @@ impl Error {
///
/// The kind of the error, such as [`VALUE_ERROR`].
pub fn kind(&self) -> ErrorKind<'_> {
- ErrorKind(&self.data.cell.kind.as_str())
+ ErrorKind(self.data.cell.kind.as_str())
}
/// Get the message of the error.
diff --git a/rust/tvm-ffi/src/extra/structural_visit.rs
b/rust/tvm-ffi/src/extra/structural_visit.rs
index fec80cdf..a27c9158 100644
--- a/rust/tvm-ffi/src/extra/structural_visit.rs
+++ b/rust/tvm-ffi/src/extra/structural_visit.rs
@@ -327,6 +327,7 @@ impl VisitInterrupt {
/// See also [`structural_visit`].
pub struct StructuralVisitorView<'a, D, Base = StructuralVisitorObj> {
runtime: StructuralVisitorHandle,
+ #[allow(clippy::type_complexity)]
_scope: PhantomData<(&'a mut (), fn(&mut D) -> Base, Rc<()>)>,
}
diff --git a/rust/tvm-ffi/src/extra/structural_walk.rs
b/rust/tvm-ffi/src/extra/structural_walk.rs
index 66651168..e92b0eeb 100644
--- a/rust/tvm-ffi/src/extra/structural_walk.rs
+++ b/rust/tvm-ffi/src/extra/structural_walk.rs
@@ -99,14 +99,14 @@ struct WalkVisitor<'a, D, const PRE_ORDER: bool> {
observer: &'a mut D,
}
-impl<'s, 'v, 'c, 'r, 'a, D, const PRE_ORDER: bool>
+impl<'v, 'c, 'r, 'a, D, const PRE_ORDER: bool>
Dispatcher<
(
AnyView<'v>,
&'c mut StructuralVisitorView<'r, WalkVisitor<'a, D, PRE_ORDER>>,
),
Option<Result<Option<VisitInterrupt>>>,
- > for &'s mut WalkVisitor<'a, D, PRE_ORDER>
+ > for &mut WalkVisitor<'a, D, PRE_ORDER>
where
for<'d, 'b> &'d mut D: Dispatcher<(AnyView<'b>, DefRegionKind),
Option<Result<WalkResult>>>,
{
@@ -171,8 +171,7 @@ where
for<'s, 'v> &'s mut D: Dispatcher<(AnyView<'v>, DefRegionKind),
Option<Result<WalkResult>>>,
{
let root = *root.as_raw_ffi_any();
- // Own the result while dropping the observer: user capture destructors can
- // unwind after the native callback has returned.
+ // Take ownership of the raw result right after the native call.
let result = match order {
WalkOrder::PreOrder => {
let mut visitor = WalkVisitor::<D, true> { observer };
@@ -180,9 +179,7 @@ where
root,
&mut visitor,
);
- let result = unsafe { Any::from_raw_ffi_any(raw) };
- drop(visitor);
- result
+ unsafe { Any::from_raw_ffi_any(raw) }
}
WalkOrder::PostOrder => {
let mut visitor = WalkVisitor::<D, false> { observer };
@@ -190,9 +187,7 @@ where
root,
&mut visitor,
);
- let result = unsafe { Any::from_raw_ffi_any(raw) };
- drop(visitor);
- result
+ unsafe { Any::from_raw_ffi_any(raw) }
}
};
visit_result_from_any(result)
diff --git a/rust/tvm-ffi/src/function.rs b/rust/tvm-ffi/src/function.rs
index 25513ab4..a71b1981 100644
--- a/rust/tvm-ffi/src/function.rs
+++ b/rust/tvm-ffi/src/function.rs
@@ -240,7 +240,7 @@ impl Function {
heap_args.resize(args_len, AnyView::new());
&mut heap_args[..args_len]
};
- (&tuple_args).fill_any_view(packed_args);
+ tuple_args.fill_any_view(packed_args);
self.call_packed(packed_args)
}
/// Call the function with the `LEN` arguments in `tuple_args`.
@@ -267,7 +267,7 @@ impl Function {
TupleType: TupleAsPackedArgs,
{
let mut packed_args = [AnyView::new(); LEN];
- (&tuple_args).fill_any_view(&mut packed_args);
+ tuple_args.fill_any_view(&mut packed_args);
self.call_packed(&packed_args)
}
/// Look up the global function registered as `name`.
diff --git a/rust/tvm-ffi/src/function_internal.rs
b/rust/tvm-ffi/src/function_internal.rs
index ed6c8ca3..4fce5b18 100644
--- a/rust/tvm-ffi/src/function_internal.rs
+++ b/rust/tvm-ffi/src/function_internal.rs
@@ -223,7 +223,10 @@ macro_rules! impl_into_arg_holder_tuple {
};
}
-impl_into_arg_holder_tuple!(;);
+impl IntoArgHolderTuple for () {
+ type Target = ();
+ fn into_arg_holder_tuple(self) -> Self::Target {}
+}
impl_into_arg_holder_tuple!(T0; 0);
impl_into_arg_holder_tuple!(T0, T1; 0, 1);
impl_into_arg_holder_tuple!(T0, T1, T2; 0, 1, 2);
diff --git a/rust/tvm-ffi/src/macros.rs b/rust/tvm-ffi/src/macros.rs
index 5bd78d5b..9e1d4839 100644
--- a/rust/tvm-ffi/src/macros.rs
+++ b/rust/tvm-ffi/src/macros.rs
@@ -687,7 +687,11 @@ macro_rules! into_typed_fn {
// Case for 0 arguments
($f:expr, $trait:ident() -> $ret_ty:ty) => {{
let _f = $f;
- move || -> $ret_ty { Ok(_f.call_tuple_with_len::<0,
_>(())?.try_into()?) }
+ move || -> $ret_ty {
+ _f.call_tuple_with_len::<0, _>(())?
+ .try_into()
+ .map_err(Into::into)
+ }
}};
// Case for 1 argument
($f:expr, $trait:ident($t0:ty) -> $ret_ty:ty) => {{
@@ -695,7 +699,9 @@ macro_rules! into_typed_fn {
move |a0: $t0| -> $ret_ty {
use $crate::function_internal::IntoArgHolderTuple;
let tuple_args = (a0,).into_arg_holder_tuple();
- Ok(_f.call_tuple_with_len::<1, _>(tuple_args)?.try_into()?)
+ _f.call_tuple_with_len::<1, _>(tuple_args)?
+ .try_into()
+ .map_err(Into::into)
}
}};
// Case for 2 arguments
@@ -704,7 +710,9 @@ macro_rules! into_typed_fn {
move |a0: $t0, a1: $t1| -> $ret_ty {
use $crate::function_internal::IntoArgHolderTuple;
let tuple_args = (a0, a1).into_arg_holder_tuple();
- Ok(_f.call_tuple_with_len::<2, _>(tuple_args)?.try_into()?)
+ _f.call_tuple_with_len::<2, _>(tuple_args)?
+ .try_into()
+ .map_err(Into::into)
}
}};
// Case for 3 arguments
@@ -713,7 +721,9 @@ macro_rules! into_typed_fn {
move |a0: $t0, a1: $t1, a2: $t2| -> $ret_ty {
use $crate::function_internal::IntoArgHolderTuple;
let tuple_args = (a0, a1, a2).into_arg_holder_tuple();
- Ok(_f.call_tuple_with_len::<3, _>(tuple_args)?.try_into()?)
+ _f.call_tuple_with_len::<3, _>(tuple_args)?
+ .try_into()
+ .map_err(Into::into)
}
}};
// Case for 4 arguments
@@ -722,7 +732,9 @@ macro_rules! into_typed_fn {
move |a0: $t0, a1: $t1, a2: $t2, a3: $t3| -> $ret_ty {
use $crate::function_internal::IntoArgHolderTuple;
let tuple_args = (a0, a1, a2, a3).into_arg_holder_tuple();
- Ok(_f.call_tuple_with_len::<4, _>(tuple_args)?.try_into()?)
+ _f.call_tuple_with_len::<4, _>(tuple_args)?
+ .try_into()
+ .map_err(Into::into)
}
}};
// Case for 5 arguments
@@ -731,7 +743,9 @@ macro_rules! into_typed_fn {
move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4| -> $ret_ty {
use $crate::function_internal::IntoArgHolderTuple;
let tuple_args = (a0, a1, a2, a3, a4).into_arg_holder_tuple();
- Ok(_f.call_tuple_with_len::<5, _>(tuple_args)?.try_into()?)
+ _f.call_tuple_with_len::<5, _>(tuple_args)?
+ .try_into()
+ .map_err(Into::into)
}
}};
// Case for 6 arguments
@@ -740,7 +754,9 @@ macro_rules! into_typed_fn {
move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4, a5: $t5| -> $ret_ty
{
use $crate::function_internal::IntoArgHolderTuple;
let tuple_args = (a0, a1, a2, a3, a4, a5).into_arg_holder_tuple();
- Ok(_f.call_tuple_with_len::<6, _>(tuple_args)?.try_into()?)
+ _f.call_tuple_with_len::<6, _>(tuple_args)?
+ .try_into()
+ .map_err(Into::into)
}
}};
// Case for 7 arguments
@@ -750,7 +766,9 @@ macro_rules! into_typed_fn {
move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4, a5: $t5, a6: $t6|
-> $ret_ty {
use $crate::function_internal::IntoArgHolderTuple;
let tuple_args = (a0, a1, a2, a3, a4, a5,
a6).into_arg_holder_tuple();
- Ok(_f.call_tuple_with_len::<7, _>(tuple_args)?.try_into()?)
+ _f.call_tuple_with_len::<7, _>(tuple_args)?
+ .try_into()
+ .map_err(Into::into)
}
}};
// Case for 8 arguments
@@ -760,7 +778,9 @@ macro_rules! into_typed_fn {
move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4, a5: $t5, a6: $t6,
a7: $t7| -> $ret_ty {
use $crate::function_internal::IntoArgHolderTuple;
let tuple_args = (a0, a1, a2, a3, a4, a5, a6,
a7).into_arg_holder_tuple();
- Ok(_f.call_tuple_with_len::<8, _>(tuple_args)?.try_into()?)
+ _f.call_tuple_with_len::<8, _>(tuple_args)?
+ .try_into()
+ .map_err(Into::into)
}
}};
}
diff --git a/rust/tvm-ffi/src/match_any_internal.rs
b/rust/tvm-ffi/src/match_any_internal.rs
index caddc78a..c999b807 100644
--- a/rust/tvm-ffi/src/match_any_internal.rs
+++ b/rust/tvm-ffi/src/match_any_internal.rs
@@ -166,6 +166,7 @@ impl<'a> Restore<crate::MutationView<'a>> for
CapabilitySource<'a> {
#[doc(hidden)]
pub trait MatchPattern<S>: Sized {
type Recovery;
+ #[allow(clippy::result_unit_err)]
fn try_match(source: S) -> Result<Matched<Self, Self::Recovery>, ()>;
}
impl<'b, T: crate::type_traits::ContainerElement, S: SourceView>
MatchPattern<&'b mut S> for T {
@@ -274,6 +275,7 @@ impl<T> RefPatternMetadata for &PatternConversionProbe<T> {
pub trait RefPatternConversion<'b, S, T> {
type Holder: std::borrow::Borrow<T>;
type Recovery;
+ #[allow(clippy::result_unit_err)]
fn try_convert_ref(
&self,
source: &'b mut S,
@@ -365,6 +367,7 @@ impl LeafLookupTable {
#[doc(hidden)]
#[inline(always)]
+ #[allow(clippy::result_unit_err)]
pub fn lookup(&self, pattern_list_id: TypeId, type_index: i32) ->
Result<Option<ArmId>, ()> {
if self.pattern_list_id != pattern_list_id {
return Err(());
diff --git a/rust/tvm-ffi/src/object.rs b/rust/tvm-ffi/src/object.rs
index a07ff29e..36c0ff51 100644
--- a/rust/tvm-ffi/src/object.rs
+++ b/rust/tvm-ffi/src/object.rs
@@ -111,7 +111,6 @@ pub unsafe trait ObjectCore: Sized + 'static {
///
/// # Returns
/// * `&mut TVMFFIObject` - The object header
- /// \return The object header
///
/// # Safety
/// The caller must have exclusive access to the header and preserve the
@@ -122,12 +121,19 @@ pub unsafe trait ObjectCore: Sized + 'static {
/// Traits for objects with extra items that follows the object
///
/// This extra trait can be helpful to implement array types and string types
+///
+/// # Safety
+/// Every allocation of `Self` must be followed by `extra_items_count`
initialized
+/// `ExtraItem`s, as `ObjectArc::new_with_extra_items` lays them out.
pub unsafe trait ObjectCoreWithExtraItems: ObjectCore {
/// type of extra items storage that follows the object
type ExtraItem;
/// Return the number of extra items
fn extra_items_count(this: &Self) -> usize;
/// Return the extra items data pointer
+ ///
+ /// # Safety
+ /// `this` must be an allocation that carries its extra items.
unsafe fn extra_items(this: &Self) -> &[Self::ExtraItem] {
let extra_items_ptr = (this as *const Self as *const
u8).add(std::mem::size_of::<Self>());
std::slice::from_raw_parts(
@@ -136,6 +142,9 @@ pub unsafe trait ObjectCoreWithExtraItems: ObjectCore {
)
}
/// Return the extra items data pointer
+ ///
+ /// # Safety
+ /// `this` must be an allocation that carries its extra items.
unsafe fn extra_items_mut(this: &mut Self) -> &mut [Self::ExtraItem] {
let extra_items_ptr = (this as *mut Self as *mut
u8).add(std::mem::size_of::<Self>());
std::slice::from_raw_parts_mut(
@@ -659,6 +668,7 @@ pub mod unsafe_ {
//---------------------
impl Object {
+ #[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
header: TVMFFIObject::new(),
@@ -768,7 +778,7 @@ impl<T: ObjectCore> ObjectArc<T> {
);
// move into the object arc ptr
Self {
- ptr: std::ptr::NonNull::new_unchecked(ptr as *mut T),
+ ptr: std::ptr::NonNull::new_unchecked(ptr),
_phantom: std::marker::PhantomData,
}
}
@@ -793,7 +803,6 @@ impl<T: ObjectCore> ObjectArc<T> {
///
/// # Returns
/// * `ObjectArc<T>` - The ObjectArc
- /// \return The ObjectArc
///
/// # Safety
/// `ptr` must own one strong reference to a live, stable managed
allocation
diff --git a/rust/tvm-ffi/src/optional.rs b/rust/tvm-ffi/src/optional.rs
index fd611fe2..a52f8709 100644
--- a/rust/tvm-ffi/src/optional.rs
+++ b/rust/tvm-ffi/src/optional.rs
@@ -47,6 +47,10 @@ use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
/// for those values; it is the pointer-sized mirror of C++'s nullable
/// `ObjectPtr`-backed optional.
///
+/// # Safety
+/// Implement only for types whose C++ `ffi::Optional<T>` uses the `TVMFFIAny`
+/// representation; for an object class it would mismatch the C++ pointer
layout.
+///
/// ```compile_fail,E0277
/// use tvm_ffi::{Array, Optional};
/// let _ = Optional::<Array<i64>>::none();
diff --git a/rust/tvm-ffi/src/string.rs b/rust/tvm-ffi/src/string.rs
index d9c6a7a5..d3eb8d82 100644
--- a/rust/tvm-ffi/src/string.rs
+++ b/rust/tvm-ffi/src/string.rs
@@ -110,7 +110,7 @@ unsafe impl ObjectCoreWithExtraItems for BytesObj {
#[inline]
/// Get the count of extra items (trailing null byte for FFI compatibility)
fn extra_items_count(this: &Self) -> usize {
- return this.data.size + 1;
+ this.data.size + 1
}
}
@@ -133,7 +133,7 @@ where
data: TVMFFIAny {
type_index: TypeIndex::kTVMFFISmallBytes as i32,
small_str_len: value.len() as u32,
- data_union: data_union,
+ data_union,
},
}
} else {
@@ -207,7 +207,7 @@ impl Eq for Bytes {}
impl PartialOrd for Bytes {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
- self.as_slice().partial_cmp(other.as_slice())
+ Some(self.cmp(other))
}
}
@@ -284,7 +284,7 @@ unsafe impl ObjectCoreWithExtraItems for StringObj {
/// Get the count of extra items (trailing null byte for FFI compatibility)
fn extra_items_count(this: &Self) -> usize {
// extra item is the trailing \0 for ffi compatibility
- return this.data.size + 1;
+ this.data.size + 1
}
}
@@ -349,7 +349,7 @@ where
data: TVMFFIAny {
type_index: TypeIndex::kTVMFFISmallStr as i32,
small_str_len: bytes.len() as u32,
- data_union: data_union,
+ data_union,
},
}
} else {
@@ -449,7 +449,7 @@ where
impl PartialOrd for String {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
- self.as_str().partial_cmp(other.as_str())
+ Some(self.cmp(other))
}
}
@@ -505,8 +505,8 @@ unsafe impl AnyCompatible for Bytes {
}
unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
- return data.type_index == TypeIndex::kTVMFFISmallBytes as i32
- || data.type_index == TypeIndex::kTVMFFIBytes as i32;
+ data.type_index == TypeIndex::kTVMFFISmallBytes as i32
+ || data.type_index == TypeIndex::kTVMFFIBytes as i32
}
unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
@@ -559,8 +559,8 @@ unsafe impl AnyCompatible for String {
}
unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
- return data.type_index == TypeIndex::kTVMFFISmallStr as i32
- || data.type_index == TypeIndex::kTVMFFIStr as i32;
+ data.type_index == TypeIndex::kTVMFFISmallStr as i32
+ || data.type_index == TypeIndex::kTVMFFIStr as i32
}
unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
diff --git a/rust/tvm-ffi/src/type_traits.rs b/rust/tvm-ffi/src/type_traits.rs
index 6e65c2a3..9a541b19 100644
--- a/rust/tvm-ffi/src/type_traits.rs
+++ b/rust/tvm-ffi/src/type_traits.rs
@@ -25,6 +25,11 @@ use tvm_ffi_sys::{TVMFFIAny, TVMFFIGetTypeInfo,
TVMFFIObject};
//-----------------------------------------------------
/// Trait to enable a value to be compatible with Any
/// Enables TryFrom/Into AnyView/Any
+///
+/// # Safety
+/// Implementations must encode and decode `TVMFFIAny` cells in the layout of
+/// their FFI type index, and every `*_after_check` function must be sound for
+/// each cell that `check_any_strict` accepts.
pub unsafe trait AnyCompatible: Sized {
/// Whether the `AnyView -> Self` conversion matches one exact leaf type.
///
@@ -76,10 +81,21 @@ pub unsafe trait AnyCompatible: Sized {
}
/// the value to copy to TVMFFIAny
+ ///
+ /// # Safety
+ /// The written cell borrows `src` without a reference and must not be used
+ /// after `src` is dropped.
unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny);
/// consume the value to move to Any
+ ///
+ /// # Safety
+ /// The previous content of `data` is overwritten without release; the
+ /// caller owns the written cell and must release it exactly once.
unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny);
- // check if the value is compatible with the type
+ /// check if the value is compatible with the type
+ ///
+ /// # Safety
+ /// `data` must be a valid `TVMFFIAny` cell.
unsafe fn check_any_strict(data: &TVMFFIAny) -> bool;
/// Additional value-preservation checks used only by `match_any!`, after
@@ -93,13 +109,23 @@ pub unsafe trait AnyCompatible: Sized {
}
/// Copy value from TVMFFIAny after checking
- /// caller must ensure that the value is compatible with the type
+ ///
+ /// # Safety
+ /// `data` must have passed `Self::check_any_strict`.
unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self;
/// the value to move from TVMFFIAny
/// NOTE: pay very careful attention to avoid memory leak!
/// - When calling from managed Any, remember to use std::mem::ManuallyDrop
+ ///
+ /// # Safety
+ /// `data` must have passed `Self::check_any_strict`. Its ownership moves
+ /// into the result, so the caller must not release `data` again.
unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self;
/// try to cast the value from AnyView
+ ///
+ /// # Safety
+ /// `data` must be a valid `TVMFFIAny` cell.
+ #[allow(clippy::result_unit_err)]
unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()>;
/// Get the type key of a type when TryCastFromAnyView fails.
fn get_mismatch_type_info(data: &TVMFFIAny) -> String {
@@ -747,7 +773,7 @@ unsafe impl<T: AnyCompatible> AnyCompatible for Option<T> {
}
unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
- return T::check_any_strict(data) || data.type_index ==
TypeIndex::kTVMFFINone as i32;
+ T::check_any_strict(data) || data.type_index == TypeIndex::kTVMFFINone
as i32
}
unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
@@ -898,16 +924,12 @@ unsafe impl AnyCompatible for () {
}
unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
- return data.type_index == TypeIndex::kTVMFFINone as i32;
+ data.type_index == TypeIndex::kTVMFFINone as i32
}
- unsafe fn copy_from_any_view_after_check(_data: &TVMFFIAny) -> Self {
- ()
- }
+ unsafe fn copy_from_any_view_after_check(_data: &TVMFFIAny) -> Self {}
- unsafe fn move_from_any_after_check(_data: &mut TVMFFIAny) -> Self {
- ()
- }
+ unsafe fn move_from_any_after_check(_data: &mut TVMFFIAny) -> Self {}
unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
if data.type_index == TypeIndex::kTVMFFINone as i32 {
diff --git a/rust/tvm-ffi/tests/test_any.rs b/rust/tvm-ffi/tests/test_any.rs
index 45120db5..c7ae479c 100644
--- a/rust/tvm-ffi/tests/test_any.rs
+++ b/rust/tvm-ffi/tests/test_any.rs
@@ -70,8 +70,8 @@ macro_rules! test_any_float {
// Test all float types with both Any and AnyView
test_any_float!(
- f32: 3.14f32, test_any_float_f32, test_any_view_float_f32,
- f64: 3.14f64, test_any_float_f64, test_any_view_float_f64
+ f32: 2.5f32, test_any_float_f32, test_any_view_float_f32,
+ f64: 2.5f64, test_any_float_f64, test_any_view_float_f64
);
#[test]
@@ -88,14 +88,14 @@ fn test_any_bool() {
// Test Any
assert_eq!(any_true.type_index(), TypeIndex::kTVMFFIBool as i32);
assert_eq!(any_false.type_index(), TypeIndex::kTVMFFIBool as i32);
- assert_eq!(bool::try_from(any_true).unwrap(), true);
- assert_eq!(bool::try_from(any_false).unwrap(), false);
+ assert!(bool::try_from(any_true).unwrap());
+ assert!(!bool::try_from(any_false).unwrap());
// Test AnyView
assert_eq!(any_view_true.type_index(), TypeIndex::kTVMFFIBool as i32);
assert_eq!(any_view_false.type_index(), TypeIndex::kTVMFFIBool as i32);
- assert_eq!(bool::try_from(any_view_true).unwrap(), true);
- assert_eq!(bool::try_from(any_view_false).unwrap(), false);
+ assert!(bool::try_from(any_view_true).unwrap());
+ assert!(!bool::try_from(any_view_false).unwrap());
}
#[test]
@@ -113,7 +113,7 @@ fn test_type_mismatch_error() {
#[test]
fn test_type_mismatch_error_message() {
- let any_none = Any::from(Option::<i32>::from(None));
+ let any_none = Any::from(None::<i32>);
// try from will try casting when possible
// Try to convert int to bool - should be ok
let err = i32::try_from(any_none).unwrap_err();
@@ -138,8 +138,8 @@ fn test_cross_type_conversion_int_to_bool() {
// Note: This test might fail depending on how try_cast_from_any_view is
implemented
// If it fails, it means the conversion isn't implemented yet
- assert_eq!(bool_true.unwrap(), true);
- assert_eq!(bool_false.unwrap(), false);
+ assert!(bool_true.unwrap());
+ assert!(!bool_false.unwrap());
}
#[test]
@@ -270,6 +270,7 @@ fn test_anyview_any_conversion_and_cloning() {
assert_eq!(any_view.debug_strong_count(), Some(1));
// Test AnyView cloning - should not affect reference count
+ #[allow(clippy::clone_on_copy)] // exercises AnyView::clone explicitly
let any_view_clone = any_view.clone();
assert_eq!(any_view.debug_strong_count(), Some(1));
assert_eq!(any_view_clone.debug_strong_count(), Some(1));
diff --git a/rust/tvm-ffi/tests/test_array.rs b/rust/tvm-ffi/tests/test_array.rs
index 794c1ab6..3b9c3d81 100644
--- a/rust/tvm-ffi/tests/test_array.rs
+++ b/rust/tvm-ffi/tests/test_array.rs
@@ -54,7 +54,7 @@ fn test_array_core_and_iteration() {
assert_eq!(array[1].ndim(), 3);
// Iteration
- let vals: Vec<f32> = array.iter().map(|t| get_val(&t)).collect();
+ let vals: Vec<f32> = array.iter().map(get_val).collect();
assert_eq!(vals, vec![10.0, 20.0]);
}
diff --git a/rust/tvm-ffi/tests/test_big_int.rs
b/rust/tvm-ffi/tests/test_big_int.rs
index ec2b3034..3a0405b2 100644
--- a/rust/tvm-ffi/tests/test_big_int.rs
+++ b/rust/tvm-ffi/tests/test_big_int.rs
@@ -245,7 +245,8 @@ fn test_big_int_from_words_normalizes() {
#[test]
fn test_big_int_native_conversions() {
- let cases: [(BigInt, Option<i64>, Option<u64>, Option<i128>,
Option<u128>); 9] = [
+ type Case = (BigInt, Option<i64>, Option<u64>, Option<i128>, Option<u128>);
+ let cases: [Case; 9] = [
(BigInt::from(0i64), Some(0), Some(0), Some(0), Some(0)),
(BigInt::from(-1i64), Some(-1), None, Some(-1), None),
(
@@ -595,6 +596,7 @@ fn test_big_int_promotion_demotion_and_mixed_operands() {
assert_eq!(&big(i64::MIN as i128) - 1i64, -(&high + 1i64));
assert_eq!(-big(i64::MIN as i128), high);
assert_eq!(&big(i64::MIN as i128) / -1i64, high);
+ #[allow(clippy::modulo_one)] // intentional: i64::MIN % -1 must not
overflow
assert_inline(&(&big(i64::MIN as i128) % -1i64), 0);
assert_eq!(BigInt::from(u64::MAX).to_string(), "18446744073709551615");
assert_eq!(1i64 + BigInt::from(u64::MAX), pow2(64));
@@ -1000,7 +1002,7 @@ fn test_big_int_random_algebraic_properties() {
];
let mut rng = XorShift(0x9E37_79B9_7F4A_7C15);
let pick = |rng: &mut XorShift| {
- if rng.next() % 4 == 0 {
+ if rng.next().is_multiple_of(4) {
pool[(rng.next() % pool.len() as u64) as usize].clone()
} else {
rng.big_int()
diff --git a/rust/tvm-ffi/tests/test_function.rs
b/rust/tvm-ffi/tests/test_function.rs
index f7e39e14..1700e2d9 100644
--- a/rust/tvm-ffi/tests/test_function.rs
+++ b/rust/tvm-ffi/tests/test_function.rs
@@ -86,7 +86,7 @@ fn test_function_call_tuple() {
// test pass by reference
let result = sum1.call_tuple_with_len::<1, _>((&1,)).unwrap();
assert_eq!(i32::try_from(result).unwrap(), 1 + offset);
- let typed_fn = |x: &i32| -> Result<i32> {
Ok(sum1.call_tuple((x,))?.try_into()?) };
+ let typed_fn = |x: &i32| -> Result<i32> {
sum1.call_tuple((x,))?.try_into() };
let result = typed_fn(&1);
assert_eq!(result.unwrap(), 1 + offset);
}
diff --git a/rust/tvm-ffi/tests/test_list.rs b/rust/tvm-ffi/tests/test_list.rs
index acf3e1be..47d8201f 100644
--- a/rust/tvm-ffi/tests/test_list.rs
+++ b/rust/tvm-ffi/tests/test_list.rs
@@ -306,9 +306,8 @@ fn test_list_insert_many_with_self_mutating_iterator() {
list.push(0).unwrap();
list.insert_many(
0,
- (1..=3).map(|i| {
+ (1..=3).inspect(|&i| {
list.push(100 + i).unwrap();
- i
}),
)
.unwrap();
@@ -320,9 +319,8 @@ fn test_list_insert_many_with_self_mutating_iterator() {
);
// `extend` appends after whatever the iterator added.
- list.extend((1..=2).map(|i| {
+ list.extend((1..=2).inspect(|&i| {
list.push(200 + i).unwrap();
- i
}))
.unwrap();
assert_eq!(
diff --git a/rust/tvm-ffi/tests/test_match_any.rs
b/rust/tvm-ffi/tests/test_match_any.rs
index 17bae80a..e1f71bb3 100644
--- a/rust/tvm-ffi/tests/test_match_any.rs
+++ b/rust/tvm-ffi/tests/test_match_any.rs
@@ -412,6 +412,8 @@ fn
direct_lookup_table_maps_runtime_indices_to_local_arm_ids() {
}
#[test]
+// `(&probe)` mirrors the receiver `match_any!` generates for autoref
specialization.
+#[allow(clippy::needless_borrow)]
fn metadata_only_accepts_exact_leaf_patterns() {
type Leaf = (Module, ());
let leaf = LeafPatternProbe::<Leaf>::new();
diff --git a/rust/tvm-ffi/tests/test_match_any_ast_lookup.rs
b/rust/tvm-ffi/tests/test_match_any_ast_lookup.rs
index 5385270b..f68d82b0 100644
--- a/rust/tvm-ffi/tests/test_match_any_ast_lookup.rs
+++ b/rust/tvm-ffi/tests/test_match_any_ast_lookup.rs
@@ -263,6 +263,8 @@ define_expr_leaves!(
);
#[test]
+// `(&probe)` mirrors the receiver `match_any!` generates for autoref
specialization.
+#[allow(clippy::needless_borrow)]
fn dispatches_representative_ast_leaf_nodes() {
register_expr_types();
diff --git a/rust/tvm-ffi/tests/test_rs_object.rs
b/rust/tvm-ffi/tests/test_rs_object.rs
index c8299ceb..a968e3c3 100644
--- a/rust/tvm-ffi/tests/test_rs_object.rs
+++ b/rust/tvm-ffi/tests/test_rs_object.rs
@@ -114,8 +114,8 @@ impl ShallowCopy for TestCxxClassBaseObj {
fn shallow_copy(&self) -> Self {
Self {
base: ShallowCopy::shallow_copy(&self.base),
- v_i64: Clone::clone(&self.v_i64),
- v_i32: Clone::clone(&self.v_i32),
+ v_i64: self.v_i64,
+ v_i32: self.v_i32,
}
}
}
diff --git a/rust/tvm-ffi/tests/test_structural_mutate.rs
b/rust/tvm-ffi/tests/test_structural_mutate.rs
index 1059b79f..bac6563c 100644
--- a/rust/tvm-ffi/tests/test_structural_mutate.rs
+++ b/rust/tvm-ffi/tests/test_structural_mutate.rs
@@ -38,9 +38,8 @@ fn strict_bool(value: AnyView<'_>) -> Option<bool> {
struct IncrementIntegers;
-impl<'receiver, 'value>
- Dispatcher<(AnyView<'value>, DefRegionKind),
Option<Result<UnchangedOr<Any>>>>
- for &'receiver mut IncrementIntegers
+impl<'value> Dispatcher<(AnyView<'value>, DefRegionKind),
Option<Result<UnchangedOr<Any>>>>
+ for &mut IncrementIntegers
{
#[inline(always)]
fn dispatch_tuple(
@@ -70,14 +69,14 @@ struct RecursiveEntryMutator {
owned_value_pointer: Option<usize>,
}
-impl<'s, 'v, 'c, 'r>
+impl<'v, 'c, 'r>
Dispatcher<
(
MutationView<'v>,
&'c mut StructuralMutatorView<'r, ManualIncrement>,
),
Option<Result<UnchangedOr<Any>>>,
- > for &'s mut ManualIncrement
+ > for &mut ManualIncrement
{
#[inline(always)]
fn dispatch_tuple(
@@ -544,7 +543,7 @@ fn
default_mutation_mode_preserves_ownership_and_unchanged_results() {
} else {
let result = mutator.default_mutate(self,
value.with_inplace_mode(mode))?;
assert!(result.is_unchanged());
- Ok(result.into())
+ Ok(result)
}
}
}
@@ -860,12 +859,10 @@ fn
consuming_callbacks_forward_permissions_without_temporary_owners() {
assert_eq!(a.size, 1);
assert_eq!(a.inplace_mode(), Allow);
assert_eq!(a.as_any_view().debug_strong_count(), Some(1));
- drop(a);
let mut value = value.with_inplace_mode(Disallow);
let b = value.field(|node| &node.b);
assert_eq!(b.inplace_mode(), Disallow);
assert_eq!(b.as_any_view().debug_strong_count(), Some(1));
- drop(b);
assert_eq!(value.as_any_view().debug_strong_count(), Some(1));
}
@@ -958,12 +955,12 @@ fn
consuming_default_descent_preserves_unchanged_and_propagates_errors() {
return if self.0 {
Err(Error::new(RUNTIME_ERROR, "child failed", ""))
} else {
- Ok(UnchangedOr::<Any>::unchanged().into())
+ Ok(UnchangedOr::<Any>::unchanged())
};
}
let result = mutator.default_mutate(self, value)?;
assert!(result.is_unchanged());
- Ok(result.into())
+ Ok(result)
}
}
for fail in [false, true] {
@@ -1069,7 +1066,7 @@ fn
callback_errors_preserve_message_and_add_object_context() {
if value.downcast_ref::<i64>().copied().is_some() {
return Err(self.0.clone());
}
- visitor.default_visit(self, &value)
+ visitor.default_visit(self, value)
}
}
@@ -1680,9 +1677,9 @@ fn recursive_mutate_returns_unchanged_or_a_replacement() {
if let Some(integer) =
value.as_any_view().downcast_ref::<i64>().copied() {
if integer >= 0 {
// Keep this input without constructing an owning return
value.
- return Ok(UnchangedOr::<Any>::unchanged().into());
+ return Ok(UnchangedOr::<Any>::unchanged());
}
- return Ok(UnchangedOr::changed(Any::from(0i64)).into());
+ return Ok(UnchangedOr::changed(Any::from(0i64)));
}
// Keep the unchanged marker if no child changed.
mutator.default_mutate(self, value).into_mutate_result()
@@ -2014,7 +2011,7 @@ impl CallbackMutateDepth {
let mutated = mutator.default_mutate(self,
MutationView::borrowed(value))?;
self.current -= 1;
self.exits += 1;
- Ok(mutated.into())
+ Ok(mutated)
}
}
@@ -2564,7 +2561,7 @@ fn mapping_preserves_post_recursion_state() {
self.depth -= 1;
assert_eq!(self.depth, depth);
self.completed += 1;
- Ok(result.into())
+ Ok(result)
}
}
let mut state = PostState::default();
diff --git a/rust/tvm-ffi/tests/test_structural_visit.rs
b/rust/tvm-ffi/tests/test_structural_visit.rs
index 90bd7171..fafeb596 100644
--- a/rust/tvm-ffi/tests/test_structural_visit.rs
+++ b/rust/tvm-ffi/tests/test_structural_visit.rs
@@ -88,12 +88,12 @@ fn
default_descent_scopes_regions_and_restores_after_halts() {
self.regions.push(outer);
let result = if level < 2 {
visitor.with_def_region_kind([Simple, Pattern][level],
|visitor| {
- visitor.visit(self, &value)
+ visitor.visit(self, value)
})
} else {
visitor.with_def_region_kind(Use, |visitor| {
let current = value;
- let result = visitor.default_visit(self, ¤t);
+ let result = visitor.default_visit(self, current);
assert_eq!(
current.downcast_ref::<Array<i64>>().cloned().unwrap().len(),
2
@@ -272,7 +272,7 @@ fn regions_compose_with_field_flags_and_function_hooks() {
kind
};
visitor
- .with_def_region_kind(requested, |visitor|
visitor.default_visit(self, &value))
+ .with_def_region_kind(requested, |visitor|
visitor.default_visit(self, value))
}
}
}
@@ -357,8 +357,9 @@ fn reflected_pattern_precedes_default_descent() {
_ => Ok(None),
}
}
- None => visitor
- .with_def_region_kind(kind, |visitor|
visitor.default_visit(self, &value)),
+ None => {
+ visitor.with_def_region_kind(kind, |visitor|
visitor.default_visit(self, value))
+ }
}
}
}
@@ -946,7 +947,7 @@ impl StraddleVisitor {
};
self.events.push(format!("enter:{label}"));
if let Some(interrupt) = visitor.with_def_region_kind(def_region_kind,
|visitor| {
- visitor.default_visit(self, &value)
+ visitor.default_visit(self, value)
})? {
return Ok(Some(interrupt));
}
@@ -1099,7 +1100,7 @@ fn visitor_errors_include_native_visit_path() {
return Err(runtime_error("visitor failed"));
}
visitor.with_def_region_kind(def_region_kind, |visitor| {
- visitor.default_visit(self, &value)
+ visitor.default_visit(self, value)
})
}
}
@@ -1155,7 +1156,7 @@ fn
visitor_interrupt_propagates_through_default_children() {
return Ok(Some(VisitInterrupt::new(7i64)));
}
visitor.with_def_region_kind(def_region_kind, |visitor| {
- visitor.default_visit(self, &value)
+ visitor.default_visit(self, value)
})
}
}
@@ -1497,7 +1498,7 @@ impl InheritedRegionProbe {
}
self.seen.push(def_region_kind);
visitor.with_def_region_kind(def_region_kind, |visitor| {
- visitor.default_visit(self, &value)
+ visitor.default_visit(self, value)
})
}
}
@@ -1754,7 +1755,7 @@ impl StatefulVisitDepth {
self.calls += 1;
let current = self.current;
self.maximum = self.maximum.max(current);
- let outcome = visitor.default_visit(self, &value);
+ let outcome = visitor.default_visit(self, value);
self.current -= 1;
outcome
}
@@ -1786,7 +1787,7 @@ fn
callback_visit_can_reenter_the_same_fn_through_visitor() {
visitor: &mut StructuralVisitorView<'_, Self>,
) -> Result<Option<VisitInterrupt>> {
self.0.set(self.0.get() + 1);
- visitor.default_visit(self, &value)
+ visitor.default_visit(self, value)
}
}
let root = Array::from_vec(vec![1i64, 2]);
@@ -1818,7 +1819,7 @@ fn
callback_visit_tuple_is_first_match_and_can_interrupt() {
visitor: &mut StructuralVisitorView<'_, Self>,
) -> Result<Option<VisitInterrupt>> {
self.0.set(self.0.get() + 1);
- visitor.default_visit(self, &value)
+ visitor.default_visit(self, value)
}
}
let root = Array::from_vec(vec![1i64, 2, 3]);
@@ -1948,16 +1949,16 @@ fn
nested_callback_visit_restores_the_outer_active_visitor() {
for default in [false, true] {
let rejected =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if default {
- visitor.default_visit(&mut other, &value)
+ visitor.default_visit(&mut other, value)
} else {
- visitor.visit(&mut other, &value)
+ visitor.visit(&mut other, value)
}
}));
assert!(rejected.is_err());
assert_eq!(other.calls, 0);
}
}
- visitor.default_visit(self, &value)
+ visitor.default_visit(self, value)
}
}
let aligned_root = Array::from_vec(vec![3_i64, 4]);
@@ -2030,7 +2031,7 @@ fn
nested_callback_visit_restores_the_outer_active_visitor() {
if !self.entered.replace(true) {
structural_visit(self.inner, Inner(self.inner_values))?;
}
- visitor.default_visit(self, &value)
+ visitor.default_visit(self, value)
}
}
let outer = Array::from_vec(vec![10i64, 20]);
@@ -2068,7 +2069,7 @@ fn
copied_views_forward_borrows_and_retain_only_explicit_owners() {
assert_eq!(copy.debug_strong_count(), Some(1));
let mut retained = None;
structural_walk(
- ©,
+ copy,
|value: AnyView<'_>| {
let copy = value;
if let Some(node) =
copy.downcast_ref::<tvm_ffi::collections::array::ArrayObj>() {
@@ -2241,7 +2242,7 @@ fn visitor_preserves_post_recursion_state() {
) -> Result<Option<VisitInterrupt>> {
let depth = self.depth;
self.depth += 1;
- let result = visitor.default_visit(self, &value)?;
+ let result = visitor.default_visit(self, value)?;
self.depth -= 1;
assert_eq!(self.depth, depth);
self.completed += 1;
diff --git a/rust/tvm-ffi/tests/test_structural_visitor_alignment.rs
b/rust/tvm-ffi/tests/test_structural_visitor_alignment.rs
index 94141b56..80c595db 100644
--- a/rust/tvm-ffi/tests/test_structural_visitor_alignment.rs
+++ b/rust/tvm-ffi/tests/test_structural_visitor_alignment.rs
@@ -97,7 +97,7 @@ impl RecordingVisitor {
// C++: return DefaultVisitExpected(value);
visitor.with_def_region_kind(def_region_kind, |visitor| {
- visitor.default_visit(self, &value)
+ visitor.default_visit(self, value)
})
}
}
diff --git a/rust/tvm-ffi/tests/test_tensor.rs
b/rust/tvm-ffi/tests/test_tensor.rs
index 9018edc9..107b3bb6 100644
--- a/rust/tvm-ffi/tests/test_tensor.rs
+++ b/rust/tvm-ffi/tests/test_tensor.rs
@@ -34,7 +34,7 @@ fn test_tensor_basic() {
assert_eq!(tensor.shape(), &shape);
assert_eq!(tensor.ndim(), 3);
assert_eq!(tensor.dtype().code, DLDataTypeCode::kDLFloat as u8);
- assert_eq!(tensor.dtype().bits, 32 as u8);
+ assert_eq!(tensor.dtype().bits, 32_u8);
assert_eq!(tensor.device().device_type, DLDeviceType::kDLCPU);
// Test strides (should be calculated correctly for row-major layout)
@@ -64,14 +64,14 @@ fn test_tensor_data_as_slice_f32() {
assert_eq!(data_slice_mut.len(), 24);
// Test that we can write to the tensor data
- for i in 0..data_slice_mut.len() {
- data_slice_mut[i] = i as f32;
+ for (i, x) in data_slice_mut.iter_mut().enumerate() {
+ *x = i as f32;
}
// Test that we can read the written data
let data_slice_read = tensor.data_as_slice::<f32>().unwrap();
- for i in 0..data_slice_read.len() {
- assert_eq!(data_slice_read[i], i as f32);
+ for (i, x) in data_slice_read.iter().enumerate() {
+ assert_eq!(*x, i as f32);
}
}
@@ -117,7 +117,7 @@ fn test_any_tensor() {
// ============================================================================
mod env_alloc {
- use std::ffi::{c_char, c_void, CStr};
+ use std::ffi::{c_char, c_void};
use tvm_ffi::tvm_ffi_sys::{
dlpack::DLTensor, DLPackManagedTensorAllocator,
TVMFFIEnvSetDLPackManagedTensorAllocator,
};
@@ -183,8 +183,8 @@ mod env_alloc {
error_ctx: *mut c_void,
set_error: unsafe extern "C" fn(*mut c_void, *const c_char, *const
c_char),
) -> i32 {
- let kind = CStr::from_bytes_with_nul(b"MemoryError\0").unwrap();
- let message = CStr::from_bytes_with_nul(b"out of test
memory\0").unwrap();
+ let kind = c"MemoryError";
+ let message = c"out of test memory";
set_error(error_ctx, kind.as_ptr(), message.as_ptr());
-1
}