tvm_ffi/extra/module.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//! [`Module`], a loaded library of functions.
20
21use crate::derive::{Object, ObjectRef};
22use crate::error::Result;
23use crate::function::Function;
24use crate::object::{Object, ObjectArc};
25use crate::string::String;
26use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
27
28//-----------------------------------------------------
29// Module
30//-----------------------------------------------------
31
32/// The object behind a [`Module`].
33#[repr(C)]
34#[derive(Object)]
35#[object(type_key = "ffi.Module", unsafe type_index = TypeIndex::kTVMFFIModule)]
36pub struct ModuleObj {
37 object: Object,
38}
39
40/// A collection of functions, such as a dynamic library, passed across
41/// languages as `ffi.Module`.
42#[repr(C)]
43#[derive(ObjectRef, Clone)]
44#[object_ref(skip_deref)]
45pub struct Module {
46 data: ObjectArc<ModuleObj>,
47}
48
49impl Module {
50 /// Load a module from a dynamic library file.
51 ///
52 /// # Arguments
53 /// * `file_name` - The path of the library.
54 ///
55 /// # Returns
56 /// The module.
57 ///
58 /// # Errors
59 /// If the library cannot be loaded.
60 pub fn load_from_file<Str: AsRef<str>>(file_name: Str) -> Result<Module> {
61 let file_name = crate::string::String::from(file_name.as_ref());
62 crate::cached_global_func!("ffi.ModuleLoadFromFile")
63 .call_tuple((file_name,))?
64 .try_into()
65 }
66
67 /// Look up a function of the module by name.
68 ///
69 /// Only this module is searched, not the modules it imports.
70 ///
71 /// # Arguments
72 /// * `name` - The name of the function.
73 ///
74 /// # Returns
75 /// The function.
76 ///
77 /// # Errors
78 ///
79 /// Returns a `ValueError` naming the function if the module has no function
80 /// `name`, as [`Function::get_global`] does for a missing global function.
81 pub fn get_function<Str: AsRef<str>>(&self, name: Str) -> Result<Function> {
82 self.lookup_function(name.as_ref(), false)
83 }
84
85 /// As [`get_function`](Self::get_function), but also searching the modules
86 /// this one imports, depth first in import order.
87 pub fn get_function_with_imports<Str: AsRef<str>>(&self, name: Str) -> Result<Function> {
88 self.lookup_function(name.as_ref(), true)
89 }
90
91 fn lookup_function(&self, name: &str, query_imports: bool) -> Result<Function> {
92 let function = crate::cached_global_func!("ffi.ModuleGetFunction").call_tuple((
93 self,
94 name,
95 query_imports,
96 ))?;
97 if function.is_none() {
98 crate::bail!(
99 crate::error::VALUE_ERROR,
100 "Module has no function '{}'",
101 name
102 );
103 }
104 function.try_into()
105 }
106
107 /// Whether the module implements the function `name`.
108 ///
109 /// Only this module is searched, not the modules it imports.
110 ///
111 /// # Arguments
112 /// * `name` - The name of the function.
113 ///
114 /// # Returns
115 /// Whether the function exists.
116 pub fn implements_function<Str: AsRef<str>>(&self, name: Str) -> Result<bool> {
117 let name = String::from(name.as_ref());
118 crate::cached_global_func!("ffi.ModuleImplementsFunction")
119 .call_tuple((self, name, false))?
120 .try_into()
121 }
122
123 /// As [`implements_function`](Self::implements_function), but also searching the modules
124 /// this one imports, depth first in import order.
125 pub fn implements_function_with_imports<Str: AsRef<str>>(&self, name: Str) -> Result<bool> {
126 let name = String::from(name.as_ref());
127 crate::cached_global_func!("ffi.ModuleImplementsFunction")
128 .call_tuple((self, name, true))?
129 .try_into()
130 }
131
132 /// Get the metadata of a function the module exports.
133 ///
134 /// Only this module is searched, not the modules it imports.
135 ///
136 /// The metadata is a JSON object whose `type_schema` entry is the
137 /// function's signature, as an export with metadata enabled records it
138 /// (see [`tvm_ffi_dll_export_typed_func!`](crate::tvm_ffi_dll_export_typed_func)).
139 ///
140 /// # Arguments
141 /// * `name` - The name of the function.
142 ///
143 /// # Returns
144 /// The metadata as a JSON string, or `None` if the function has none.
145 pub fn get_function_metadata<Str: AsRef<str>>(&self, name: Str) -> Result<Option<String>> {
146 let name = String::from(name.as_ref());
147 crate::cached_global_func!("ffi.ModuleGetFunctionMetadata")
148 .call_tuple((self, name, false))?
149 .try_into()
150 }
151
152 /// As [`get_function_metadata`](Self::get_function_metadata), but also searching the modules
153 /// this one imports, depth first in import order.
154 pub fn get_function_metadata_with_imports<Str: AsRef<str>>(
155 &self,
156 name: Str,
157 ) -> Result<Option<String>> {
158 let name = String::from(name.as_ref());
159 crate::cached_global_func!("ffi.ModuleGetFunctionMetadata")
160 .call_tuple((self, name, true))?
161 .try_into()
162 }
163
164 /// Get the doc string of a function the module exports.
165 ///
166 /// Only this module is searched, not the modules it imports.
167 ///
168 /// The doc string is the one the export recorded (see
169 /// [`tvm_ffi_dll_export_typed_func_doc!`](crate::tvm_ffi_dll_export_typed_func_doc)).
170 ///
171 /// # Arguments
172 /// * `name` - The name of the function.
173 ///
174 /// # Returns
175 /// The doc string, or `None` if the function has none.
176 pub fn get_function_doc<Str: AsRef<str>>(&self, name: Str) -> Result<Option<String>> {
177 let name = String::from(name.as_ref());
178 crate::cached_global_func!("ffi.ModuleGetFunctionDoc")
179 .call_tuple((self, name, false))?
180 .try_into()
181 }
182
183 /// As [`get_function_doc`](Self::get_function_doc), but also searching the modules
184 /// this one imports, depth first in import order.
185 pub fn get_function_doc_with_imports<Str: AsRef<str>>(
186 &self,
187 name: Str,
188 ) -> Result<Option<String>> {
189 let name = String::from(name.as_ref());
190 crate::cached_global_func!("ffi.ModuleGetFunctionDoc")
191 .call_tuple((self, name, true))?
192 .try_into()
193 }
194}