tvm_ffi/lib.rs
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19//! Rust bindings of TVM FFI, the open ABI and FFI for machine learning
20//! systems.
21//!
22//! Values cross the boundary as [`Any`] and [`AnyView`]. Objects, such as
23//! [`Array`], [`Map`], [`Tensor`] and types defined with [`rs_object`], are
24//! reference counted and shared with C++ and Python. A [`Function`] is
25//! callable from every language, and an [`Error`] raised in one arrives in
26//! the others.
27//!
28//! # Examples
29//!
30//! ```standalone_crate
31//! use tvm_ffi::{Array, Function, Result};
32//!
33//! let sum = |xs: Array<i64>| -> Result<i64> { Ok(xs.iter().sum()) };
34//! Function::register_global_typed("my_ext.sum", sum, "Sum the elements.")?;
35//!
36//! let sum = Function::get_global("my_ext.sum")?;
37//! let total = sum.call_tuple((Array::from_vec(vec![1_i64, 2, 3]),))?;
38//! assert_eq!(i64::try_from(total)?, 6);
39//! # Ok::<(), tvm_ffi::Error>(())
40//! ```
41//!
42//! # FFI contracts
43//!
44//! Some guarantees rest on contracts every language keeps, which Rust cannot
45//! check:
46//!
47//! * An `ffi.String` holds UTF-8, so [`String::as_str`] does not validate it.
48//! * Types, functions and attributes register during static initialization,
49//! such as in a [`static_init_block!`], before other threads read them:
50//! readers of the runtime's tables take no lock.
51//! * A type key describes the same type in every library that declares it;
52//! see [`rs_object`].
53//! * A [`TensorView`] received as a function argument is valid only during
54//! the call, and so is an [`Any`] holding a `DLTensor*` converted from it
55//! or from an [`AnyView`].
56//! * A registered structural visit or mutate hook uses the visitor or
57//! mutator only through its arguments, during the call, and does not keep
58//! it.
59#![warn(missing_docs)]
60
61// Lets macro-generated `::tvm_ffi` paths resolve inside this crate too.
62extern crate self as tvm_ffi;
63
64pub mod any;
65pub mod big_int;
66pub mod collections;
67pub mod derive;
68pub mod device;
69pub mod dtype;
70pub mod enum_ref;
71pub mod error;
72pub mod extra;
73pub mod function;
74#[doc(hidden)]
75pub mod function_internal;
76#[doc(hidden)]
77pub mod macros;
78#[doc(hidden)]
79pub mod match_any_internal;
80pub mod object;
81pub mod optional;
82pub mod reflection;
83pub mod rvalue_ref;
84pub mod static_init;
85pub mod string;
86pub mod type_traits;
87mod util;
88pub use tvm_ffi_sys;
89
90pub use crate::any::{Any, AnyView};
91pub use crate::big_int::BigInt;
92pub use crate::collections::array::Array;
93pub use crate::collections::list::List;
94pub use crate::collections::map::Map;
95pub use crate::collections::shape::Shape;
96pub use crate::collections::tensor::{Tensor, TensorView};
97pub use crate::dtype::DLDataTypeExt;
98pub use crate::enum_ref::EnumRef;
99pub use crate::error::{
100 ATTRIBUTE_ERROR, INDEX_ERROR, INTERNAL_ERROR, KEY_ERROR, OVERFLOW_ERROR, RUNTIME_ERROR,
101 TYPE_ERROR, VALUE_ERROR, ZERO_DIVISION_ERROR,
102};
103pub use crate::error::{Error, ErrorKind, Result};
104pub use crate::extra::dispatch::{Dispatcher, IntoDispatcher};
105pub use crate::extra::module::Module;
106pub use crate::extra::structural_eq_hash::{
107 StructuralOptions, get_first_structural_mismatch, get_first_structural_mismatch_with,
108 structural_equal, structural_equal_with, structural_hash, structural_hash_with,
109};
110pub use crate::extra::structural_map::structural_map;
111pub use crate::extra::structural_mutate::{
112 InplaceMode, MutationView, StructuralMutatorView, structural_mutate,
113};
114pub use crate::extra::structural_visit::{
115 DefRegionKind, StructuralVisitorView, VisitInterrupt, structural_visit,
116};
117pub use crate::extra::structural_walk::{IntoWalkResult, WalkOrder, WalkResult, structural_walk};
118pub use crate::extra::unchanged::{Unchanged, UnchangedOr};
119pub use crate::function::Function;
120pub use crate::object::{Object, ObjectArc, ObjectCore, ObjectRef, ObjectRefCore};
121pub use crate::optional::Optional;
122pub use crate::static_init::run_static_init_blocks;
123pub use crate::string::{Bytes, String};
124pub use crate::type_traits::{AnyCompatible, IntoArg};
125/// Generate runtime type dispatch from the `prefix_*` methods of an impl.
126///
127/// `#[dispatch(prefix, (First, Args...), Ret)]` on an inherent impl makes its
128/// `prefix_*` methods handlers and adds a `dispatch(first, args...) ->
129/// Option<Ret>` method. `dispatch` calls the first handler, in source order,
130/// whose first parameter matches the runtime type of `first`, and returns
131/// `None` when no handler matches. The macro also implements [`Dispatcher`]
132/// for `&Self` or `&mut Self`, so the type can drive [`structural_walk`] and
133/// the other traversals, whose engines call it and run their own default
134/// recursion; no prefix has a reserved meaning. Handlers without an `inline`
135/// attribute are marked `#[inline(always)]`.
136///
137/// # Arguments
138///
139/// * `prefix` - The handler name prefix; `describe` selects `describe_int`,
140/// `describe_str` and so on.
141/// * `(First, Args...)` - The complete input tuple. `First`, the value to
142/// match, is `AnyView<'_>` or [`MutationView<'_>`], including aliases.
143/// `Args` are passed through: each handler takes a leading prefix of them
144/// without cloning, and need not take all of them.
145/// * `Ret` - The result type. A handler's result is converted with
146/// `Into<Ret>`. When both the handler's result and `Ret` are written
147/// `Result<..>`, the success value is converted instead, so a
148/// `Result<UnchangedOr<MyPair>>` handler fits a `Result<UnchangedOr<Any>>`
149/// dispatcher.
150///
151/// # Handlers
152///
153/// A handler's first parameter selects what it matches, as for
154/// [`match_any!`]: an owned FFI value such as `i64` or `Array<Any>`, converted
155/// strictly; `&Type` (such as `&Array<i64>` or `&tvm_ffi::String`) or
156/// `&NodeObj`, which borrow the value or the object node in place without
157/// changing a reference count; `MutationView<'_, T>`,
158/// which keeps the in-place mode; or `AnyView<'_>`, which
159/// matches every value and must be the last handler.
160///
161/// Only the outer `None` means that no handler matched: a handler error, or a
162/// `None` inside `Ret`, is final. Handlers share one receiver, `&self` or
163/// `&mut self`, and the same method generics and bounds; shared generics must
164/// occur in the receiver, the input tuple or `Ret`. Use the same lifetime name
165/// in an input and `Ret` to return a borrow of that input; elided output
166/// lifetimes borrow the receiver. Handler-level `cfg` attributes are not
167/// supported; configure the whole impl instead. Generate one dispatcher per
168/// type; when inference is ambiguous, give the expected result type.
169///
170/// # Examples
171///
172/// ```
173/// use tvm_ffi::{dispatch, AnyView};
174///
175/// struct Describer;
176///
177/// #[dispatch(describe, (AnyView<'_>,), String)]
178/// impl Describer {
179/// fn describe_int(&self, value: i64) -> String {
180/// format!("integer {value}")
181/// }
182///
183/// fn describe_str(&self, value: &tvm_ffi::String) -> String {
184/// format!("string {}", value.as_str())
185/// }
186/// }
187///
188/// let text = tvm_ffi::String::from("hi");
189/// assert_eq!(Describer.dispatch(AnyView::from(&1_i64)).as_deref(), Some("integer 1"));
190/// assert_eq!(Describer.dispatch(AnyView::from(&text)).as_deref(), Some("string hi"));
191/// assert_eq!(Describer.dispatch(AnyView::from(&1.5_f64)), None);
192/// ```
193///
194/// [`MutationView<'_>`]: crate::MutationView
195/// [`Dispatcher`]: crate::Dispatcher
196/// [`structural_walk`]: crate::structural_walk
197pub use tvm_ffi_macros::dispatch;
198
199/// Match the runtime type of a value, the way `match` matches an enum.
200///
201/// The value is an [`Any`], an [`AnyView`], a managed reference or a
202/// [`MutationView`]. It is evaluated once and taken by value; write `&value`
203/// to keep it. Arms are tried in order, and the first arm whose type matches
204/// runs; a guard that is false moves on to the next arm. The last arm must be
205/// an unguarded `_ => ...`, since new types can be registered at any time.
206///
207/// * `Type(name)` binds an owned value of `Type`, such as `i64` or
208/// `Array<Any>`.
209/// * `Type(ref name)` borrows a managed reference, and `NodeObj(ref name)`
210/// borrows the object node, without changing its reference count.
211/// * `MutationView<Type>(name)` moves the in-place mode into a
212/// typed view.
213///
214/// Matching is strict: an `i64` arm does not match a stored `f64`, and a value
215/// is never truncated. Type aliases and qualified paths may name `Type`. Typed
216/// `MutationView` arms do not match a `Map`, including a nested one; use
217/// `MutationView<Any>` for those. Ordinary `Map<K, V>` arms do match.
218///
219/// While an arm borrows the value, it must not modify an `ffi.List` or
220/// `ffi.Dict` that holds the value, which may be the borrow's only owner.
221///
222/// # Examples
223///
224/// ```
225/// use tvm_ffi::{match_any, Any, Array};
226///
227/// fn kind(value: &Any) -> String {
228/// match_any! {
229/// value {
230/// i64(n) => format!("integer {n}"),
231/// tvm_ffi::String(s) => format!("string {}", s.as_str()),
232/// Array<Any>(arr) => format!("array of {} items", arr.len()),
233/// _ => "something else".to_string(),
234/// }
235/// }
236/// }
237///
238/// assert_eq!(kind(&Any::from(42_i64)), "integer 42");
239/// assert_eq!(kind(&Any::from(Array::from_vec(vec![1_i64, 2, 3]))), "array of 3 items");
240/// assert_eq!(kind(&Any::from(1.5_f64)), "something else");
241/// ```
242pub use tvm_ffi_macros::match_any;
243
244/// Define an object type in Rust that every language can use.
245///
246/// `#[rs_object(type_key = "type.Key", options...)]` registers the struct as an object
247/// type with the reflection of every field, so that structural equality and
248/// hashing, `repr`, deep copy and Python see the fields. The first field,
249/// `base_`, is the parent type's object, embedded at the start of the struct:
250/// `base_: Object` for a type under `ffi.Object`; the trailing `_` leaves
251/// `base` free for a reflected field. Declare the managed reference with
252/// [`#[derive(ObjectRef)]`](derive::ObjectRef).
253///
254/// The macro adds to the struct:
255///
256/// * `#[repr(C)]` and `Deref` to the parent's object, so `obj.field` reads the
257/// fields of both.
258/// * `MyPairObj::new(base_, fields...)`, which takes the fields in order: a
259/// scalar (`bool`, an integer or a float) as its own type, so that a literal
260/// infers as it, and any other field as `impl Into<T>`. This is the
261/// object-level allocator, which sees only tokens and so cannot tell an
262/// object reference from a value; a constructor on the reference takes an
263/// object reference as [`impl IntoArg<T>`](IntoArg), as the
264/// ones `tvm-ffi-stubgen` generates do.
265///
266/// # Arguments
267///
268/// * `type_key = "type.Key"` - The type key, required.
269/// * `final` - The type has no subtypes.
270/// * `immutable` - Shared objects of the type are never mutated, so its
271/// references cross threads when its fields can
272/// ([`ImmutableObject`](crate::object::ImmutableObject)); a field, own or
273/// inherited, cannot be `writable`. Every subtype must be `immutable` too.
274/// * `s_eq_hash_kind = "TreeNode"` - The [`SEqHashKind`](crate::reflection::SEqHashKind) of structural
275/// equality; by default the parent's. Structural equality and hashing see
276/// the fields only when the type or an ancestor has one, and otherwise fail
277/// with a `TypeError`.
278/// * `child_slots = N`, `child_slots_can_overflow = bool` - Type indices kept
279/// for subtypes; 0 and `true` by default.
280/// * `reflection = path` - A `fn(&mut ObjectDef<Self>)` that registers the
281/// type's methods, under the constraints of
282/// [`ObjectDef`](crate::reflection::ObjectDef).
283/// * `crate = path` - Where the generated code finds tvm-ffi, for a crate that
284/// depends on it only through a re-export; by default `tvm_ffi`.
285///
286/// A field takes `#[reflect(writable, seq_hash_ignore, ...)]` for the
287/// [`FieldFlags`](crate::reflection::FieldFlags) of those names, and `name = "..."` or `doc = "..."` to
288/// register it under another name or with a doc string, by default its `///`
289/// comment. As a C++ `def_rw` field, a `writable` field can be replaced
290/// through reflection, such as from Python, while the object is shared.
291///
292/// # Requirements
293///
294/// A field's type must implement `AnyCompatible` and `Clone`; an `init_off`
295/// field's type must take all-zero bytes as a value. An optional field is an
296/// `Option` of an object reference or an [`Optional`] of any other value. The parent's object must
297/// implement `ShallowCopy` and `UnsafeInit`, as `rs_object` types and
298/// `#[object(rs_parent)]` bindings, such as the non-final ones `tvm-ffi-stubgen`
299/// generates, do.
300///
301/// # Registration
302///
303/// The type registers when its library loads, as a C++ type does in a static
304/// init block, with its fields, methods, `__ffi_new__` and, unless the methods
305/// define it, `__ffi_init__`; under a binding whose library is not loaded
306/// yet, it registers on its first `type_index()` after that library loads. A
307/// key already registered, by another library or a binding, must describe the
308/// same type: `type_index()` checks its parent, depth and size, not its
309/// fields.
310///
311/// Registrations from one library hold that library's lock, so they do not
312/// race each other; libraries that each link tvm-ffi have a lock each. The
313/// runtime's type table is not locked otherwise, and its readers take no
314/// lock: as for C++, types register during static initialization, before
315/// other threads use them or load a library that registers types. A type
316/// that registers lazily, under a binding loaded later, must take its first
317/// `type_index()` under the same rule.
318///
319/// # Examples
320///
321/// ```standalone_crate
322/// use tvm_ffi::derive::ObjectRef;
323/// use tvm_ffi::{rs_object, Object, ObjectArc};
324///
325/// #[rs_object(type_key = "my_ext.MyPair", final)]
326/// pub struct MyPairObj {
327/// base_: Object,
328/// pub first: i64,
329/// #[reflect(seq_hash_ignore)]
330/// pub second: tvm_ffi::String,
331/// }
332///
333/// #[derive(Clone, ObjectRef)]
334/// pub struct MyPair {
335/// data: ObjectArc<MyPairObj>,
336/// }
337///
338/// let pair = MyPair::from_object(MyPairObj::new(Object::new(), 1, "one"));
339/// assert_eq!(pair.first, 1);
340/// assert_eq!(pair.second.as_str(), "one");
341/// ```
342pub use tvm_ffi_macros::rs_object;
343
344pub use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
345pub use tvm_ffi_sys::{DLDataType, DLDataTypeCode, DLDevice, DLDeviceType};