Skip to main content

tvm_tirx/ir/
op_def.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
20//! Operator registration. An [`OpDef`] registers an [`Op`] with a signature of [`sig`]
21//! descriptors, from which its call validator is generated, and attribute values keyed by an
22//! [`AttrKey`], such as the shared ones in [`op_attr`].
23
24use std::any::TypeId;
25use std::marker::PhantomData;
26
27use tvm_ffi::reflection::NativeFunction;
28use tvm_ffi::{Any, AnyView, Array, Error, ObjectRefCore, Result, String, TYPE_ERROR, VALUE_ERROR};
29
30use super::attrs::Attrs;
31use super::expr::{CallObj, Expr, Var};
32use super::op::{Op, OpObj};
33use super::r#type::Type;
34use super::stmt::RegionStmtObj;
35use sig::{Checks, Specs};
36
37/// A chain of steps that registers a new operator.
38///
39/// Each step updates the registry at once, and a failed step skips the rest. The chain completes
40/// when it is dropped, panicking with the error of a failed step, or by [`OpDef::op`], which
41/// returns it. Register an operator before building IR with it, as a
42/// [`tvm_ffi::static_init_block!`] does.
43///
44/// A hook, such as the one [`OpDef::set_infer_type`] sets, reports failure through its `Result`; a
45/// panic in it aborts the process, since it would unwind into native code.
46///
47/// # Examples
48///
49/// ```standalone_crate
50/// use tvm_tirx::ir::op_attr::CALL_EFFECT_KIND;
51/// use tvm_tirx::ir::sig::{self, IntExpr};
52/// use tvm_tirx::ir::{
53///     Call, CallEffectKind, CallObj, Op, OpDef, PrimType, PrimVar, Type, Var, UNKNOWN_LOC,
54/// };
55/// use tvm_tirx::script::script;
56/// use tvm_tirx::tvm_ffi::{self, Result};
57///
58/// fn first_arg_type(call: &CallObj) -> Result<Type> {
59///     Ok(call.args[0].ty.clone())
60/// }
61///
62/// tvm_ffi::static_init_block! {
63///     OpDef::new("my_ext.clamp", "Clamp an index to a bound.")
64///         .signature((sig::arg::<IntExpr>("index", ""), sig::arg::<IntExpr>("bound", "")))
65///         .set_infer_type(first_arg_type)
66///         .set_attr(CALL_EFFECT_KIND, CallEffectKind::Pure);
67/// }
68///
69/// let clamp = Op::get("my_ext.clamp")?;
70/// let i = PrimVar::new("i", PrimType::int(32), UNKNOWN_LOC);
71/// let call = Call::new(None, clamp, [&i, &i], None, Vec::<Type>::new(), UNKNOWN_LOC)?;
72/// assert_eq!(script(&call.ty)?, "T.int32");
73/// call.validate()?;
74/// # Ok::<(), tvm_ffi::Error>(())
75/// ```
76pub struct OpDef(Option<Result<Op>>);
77
78impl OpDef {
79    /// Register a new operator `name` and start its chain (`ir.RegisterOp`).
80    ///
81    /// The indentation `doc` shares is removed. A name already registered fails the chain with an
82    /// `AttributeError`.
83    pub fn new(name: &str, doc: &str) -> Self {
84        let registered = tvm_ffi::cached_global_func!("ir.RegisterOp")
85            .call_tuple((String::from(name), String::from(doc_text(doc))));
86        Self(Some(registered.and_then(|_| Op::get(name))))
87    }
88
89    /// Complete the chain now, instead of when it is dropped, and return the operator.
90    ///
91    /// # Errors
92    ///
93    /// Returns the error of the step that failed, which dropping the chain would panic with, or of
94    /// the `ir.expose_op` receiver.
95    pub fn op(mut self) -> Result<Op> {
96        complete(self.take())
97    }
98
99    /// Set the signature of the operator to `specs`, a descriptor of [`sig`] or a tuple of them in
100    /// argument order.
101    ///
102    /// The validator generated from it checks a Call's argument counts, argument types and attrs,
103    /// unless a custom validator is set.
104    pub fn signature<S: Specs>(self, specs: S) -> Self {
105        let mut description = sig::Description::default();
106        specs.describe(&mut description);
107        let lists = description.into_lists().map(Array::from_vec);
108        let args: Vec<AnyView> = lists.iter().map(AnyView::from).collect();
109        let def = self.invoke("_set_signature", &args).then(|op| {
110            if !op.validator_is_custom() {
111                let hook: NativeFunction<(&CallObj,)> = sig::validate::<S::Checks>.into();
112                // SAFETY: an operator validator is a `void(const CallObj*)` hook.
113                op.write_validator(unsafe { hook.into_any() }, false);
114            }
115            Ok(())
116        });
117        match <S::Checks as Checks>::ATTRS_TYPE_KEY {
118            Some(key) => def.attrs_type_key(key),
119            None => def,
120        }
121    }
122
123    /// Append the description of the value argument `name`, without changing what the validator
124    /// checks.
125    pub fn add_arg(self, name: &str, doc: &str) -> Self {
126        let (name, doc) = (String::from(name), String::from(doc));
127        self.invoke("add_arg", &[AnyView::from(&name), AnyView::from(&doc)])
128    }
129
130    /// Append the description of the type argument `name`, without changing what the validator
131    /// checks.
132    pub fn add_ty_arg(self, name: &str, doc: &str) -> Self {
133        let (name, doc) = (String::from(name), String::from(doc));
134        self.invoke("add_ty_arg", &[AnyView::from(&name), AnyView::from(&doc)])
135    }
136
137    /// Set the type of `Call.attrs` to the type registered as `key`; an unregistered `key` fails
138    /// the chain with an `InternalError`.
139    pub fn attrs_type_key(self, key: &str) -> Self {
140        let key = String::from(key);
141        self.invoke("set_attrs_type_key", &[AnyView::from(&key)])
142    }
143
144    /// Register the value of the attribute `key` for the operator; a value already registered
145    /// fails the chain with a `ValueError`, and an opaque pointer with a `TypeError`.
146    pub fn set_attr<T: Into<Any>>(self, key: AttrKey<T>, value: impl Into<T>) -> Self {
147        let value: T = value.into();
148        self.value_attr(key.name, value.into(), false)
149    }
150
151    /// Register the value of the attribute `key` for the operator, replacing a value already
152    /// registered; an opaque pointer fails the chain with a `TypeError`.
153    pub fn replace_attr<T: Into<Any>>(self, key: AttrKey<T>, value: impl Into<T>) -> Self {
154        let value: T = value.into();
155        self.value_attr(key.name, value.into(), true)
156    }
157
158    /// Remove the operator's value of the attribute `key`; a missing value is ignored, and live
159    /// [`OpAttrMap`](crate::ir::OpAttrMap)s see the removal.
160    pub fn reset_attr<T>(self, key: AttrKey<T>) -> Self {
161        let key = String::from(key.name);
162        self.invoke("reset_attr", &[AnyView::from(&key)])
163    }
164
165    /// Set the type inference of the operator, its `FInferType`, to `infer`, a function or a
166    /// closure that captures nothing.
167    ///
168    /// It gives the result type of a Call that has none; [`op_attr::FIXED_RETURN_TYPE`] takes
169    /// precedence. A second one fails the chain with a `ValueError`.
170    pub fn set_infer_type<F>(self, infer: F) -> Self
171    where
172        F: Fn(&CallObj) -> Result<Type> + Copy + 'static,
173    {
174        let hook: NativeFunction<(&CallObj,), Type> = infer.into();
175        // SAFETY: `FInferType` holds `Type(const CallObj*)` hooks.
176        self.attr("FInferType", unsafe { hook.into_any() }, false)
177    }
178
179    /// Set a custom validator of the operator, `validate`, a function or a closure that captures
180    /// nothing.
181    ///
182    /// [`Call::validate`](crate::ir::Call::validate) runs it instead of the generated one. A second
183    /// one fails the chain with a `ValueError`.
184    pub fn set_validator<F>(self, validate: F) -> Self
185    where
186        F: Fn(&CallObj) -> Result<()> + Copy + 'static,
187    {
188        let hook: NativeFunction<(&CallObj,)> = validate.into();
189        self.then(|op| {
190            if op.validator_is_custom() {
191                tvm_ffi::bail!(
192                    VALUE_ERROR,
193                    "Validator of {} is already registered",
194                    op.name.as_str()
195                );
196            }
197            // SAFETY: an operator validator is a `void(const CallObj*)` hook.
198            op.write_validator(unsafe { hook.into_any() }, true);
199            Ok(())
200        })
201    }
202
203    /// Set the body parameters of the operator's regions, its `FRegionGetBodyParams`, to
204    /// `body_params`, a function or a closure that captures nothing; this makes the operator a
205    /// region operation.
206    ///
207    /// The `RegionStmt` constructor checks a region's body parameters against it. A second hook
208    /// fails the chain with a `ValueError`.
209    pub fn set_region_body_params<F>(self, body_params: F) -> Self
210    where
211        F: Fn(&CallObj) -> Result<Array<Var>> + Copy + 'static,
212    {
213        let hook: NativeFunction<(&CallObj,), Array<Var>> = body_params.into();
214        // SAFETY: `FRegionGetBodyParams` holds `Array<Var>(const CallObj*)` hooks.
215        self.attr("FRegionGetBodyParams", unsafe { hook.into_any() }, false)
216    }
217
218    /// Set the check of the operator's regions, its `FRegionValidate`, to `validate`, a function or
219    /// a closure that captures nothing.
220    ///
221    /// The `RegionStmt` constructor runs it on a complete region statement. A second check fails
222    /// the chain with a `ValueError`.
223    pub fn set_region_validate<F>(self, validate: F) -> Self
224    where
225        F: Fn(&RegionStmtObj) -> Result<()> + Copy + 'static,
226    {
227        let hook: NativeFunction<(&RegionStmtObj,)> = validate.into();
228        // SAFETY: `FRegionValidate` holds `void(const RegionStmtObj*)` hooks.
229        self.attr("FRegionValidate", unsafe { hook.into_any() }, false)
230    }
231
232    /// [`attr`](Self::attr) for a value that is not a hook. Native code calls an opaque pointer
233    /// in a hook column as a function, and operator attributes live for the process, so only the
234    /// hook setters store one.
235    fn value_attr(self, key: &str, value: Any, replace: bool) -> Self {
236        if value.type_index() == tvm_ffi::TypeIndex::kTVMFFIOpaquePtr as i32 {
237            let error =
238                tvm_ffi::format_err!(TYPE_ERROR, "Attribute {key} cannot be an opaque pointer");
239            return self.then(|_| Err(error));
240        }
241        self.attr(key, value, replace)
242    }
243
244    fn attr(self, key: &str, value: Any, replace: bool) -> Self {
245        let key = String::from(key);
246        self.invoke(
247            "_set_attr",
248            &[AnyView::from(&key), AnyView::from(&value), AnyView::from(&replace)],
249        )
250    }
251
252    /// Call the `ir.Op` method `method` on the operator with `args`.
253    fn invoke(self, method: &str, args: &[AnyView]) -> Self {
254        self.then(|op| {
255            let packed: Vec<AnyView> =
256                std::iter::once(AnyView::from(op)).chain(args.iter().copied()).collect();
257            tvm_ffi::reflection::get_method("ir.Op", method)?.call_packed(&packed)?;
258            Ok(())
259        })
260    }
261
262    fn then(mut self, step: impl FnOnce(&Op) -> Result<()>) -> Self {
263        Self(Some(self.take().and_then(|op| step(&op).map(|_| op))))
264    }
265
266    /// The state of the chain, which leaves nothing for `drop` to complete.
267    fn take(&mut self) -> Result<Op> {
268        self.0.take().expect("an `OpDef` is completed once")
269    }
270}
271
272impl Drop for OpDef {
273    fn drop(&mut self) {
274        // Dropped while a panic unwinds, the chain did not finish, and a second panic would abort.
275        if std::thread::panicking() {
276            return;
277        }
278        if let Some(Err(error)) = self.0.take().map(complete) {
279            panic!("{}: {}", error.kind(), error.message());
280        }
281    }
282}
283
284/// The key of an operator attribute: its name and the type `T` of its values.
285///
286/// [`op_attr`] and [`tirx::op_attr`](crate::tirx::op_attr) have the keys of the built-in
287/// attributes; [`AttrKey::new`] names another.
288pub struct AttrKey<T> {
289    name: &'static str,
290    value: PhantomData<fn() -> T>,
291}
292
293impl<T> AttrKey<T> {
294    /// Create the key of the attribute `name`, whose values are `T`.
295    pub const fn new(name: &'static str) -> Self {
296        Self { name, value: PhantomData }
297    }
298
299    /// Return the name of the attribute, which [`Op::attr_map`] reads the column of.
300    pub const fn name(&self) -> &'static str {
301        self.name
302    }
303}
304
305impl<T> Clone for AttrKey<T> {
306    fn clone(&self) -> Self {
307        *self
308    }
309}
310
311impl<T> Copy for AttrKey<T> {}
312
313/// The keys of the operator attributes of the shared IR.
314pub mod op_attr {
315    use super::{AttrKey, CallEffectKind};
316    use crate::ir::r#type::Type;
317
318    /// The runtime effect of a call, `TCallEffectKind`.
319    pub const CALL_EFFECT_KIND: AttrKey<CallEffectKind> = AttrKey::new("TCallEffectKind");
320    /// The result type of every call, `TFixedReturnType`, which takes precedence over
321    /// `FInferType`.
322    pub const FIXED_RETURN_TYPE: AttrKey<Type> = AttrKey::new("TFixedReturnType");
323}
324
325/// The runtime effect of an operator call: the value of [`op_attr::CALL_EFFECT_KIND`].
326#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
327#[repr(i64)]
328pub enum CallEffectKind {
329    /// An annotation, such as `likely`, which can be translated to the identity.
330    ExprAnnotation = 0,
331    /// A pure function, which does not interact with any external state.
332    Pure = 1,
333    /// A function that may read from states, such as memory.
334    ReadState = 2,
335    /// A function that may read from and write to states, such as memory; also
336    /// [`CallEffectKind::Opaque`].
337    UpdateState = 3,
338    /// A special intrinsic that annotates call arguments, valid only as a direct argument to a
339    /// call.
340    SpecialCallArg = 4,
341    /// Opaque information embedded in the expression, which cannot be generated as code.
342    EmbedInfo = 5,
343    /// A function that changes the control flow.
344    ControlJump = 6,
345}
346
347impl CallEffectKind {
348    /// An opaque function, about which nothing can be assumed: the same value as
349    /// [`CallEffectKind::UpdateState`].
350    #[allow(non_upper_case_globals)]
351    pub const Opaque: Self = Self::UpdateState;
352}
353
354impl From<CallEffectKind> for Any {
355    fn from(kind: CallEffectKind) -> Self {
356        Any::from(kind as i64)
357    }
358}
359
360/// Signature descriptors for [`OpDef::signature`].
361///
362/// [`arg`](sig::arg) and [`ty_arg`](sig::ty_arg) are fixed value and type arguments,
363/// [`var_args`](sig::var_args) and [`var_ty_args`](sig::var_ty_args) variadic tails, and
364/// [`call_attrs`](sig::call_attrs) the type of `Call.attrs`. A node type accepts an instance of it,
365/// and the typed expressions such as [`PrimExpr`](super::PrimExpr) and [`PrimVar`](super::PrimVar)
366/// also check its type; implement [`ArgType`](sig::ArgType) for another check.
367pub mod sig {
368    use super::*;
369    use crate::ir::expr::VarObj;
370    use tvm_ffi::type_traits::{AnyCompatible, DowncastRefFromAny};
371    use tvm_ffi::ObjectCore;
372
373    /// A check of an argument against a type.
374    ///
375    /// Every managed reference that is [`AnyCompatible`] implements it with its strict check;
376    /// implement it for another check, as [`TensorVar`](crate::tirx::TensorVar) does.
377    pub trait ArgType: 'static {
378        /// Return whether `value`, which is not None, is accepted, without converting it.
379        fn check(value: AnyView<'_>) -> bool;
380        /// Return the expected type, for an error.
381        fn type_str() -> std::string::String;
382        /// Describe a rejected value, for an error.
383        ///
384        /// By default, the description is the type key of `value`.
385        fn mismatch(value: AnyView<'_>) -> std::string::String {
386            tvm_ffi::reflection::type_key(value.type_index()).unwrap_or_default().to_string()
387        }
388    }
389
390    impl<T: ObjectRefCore + AnyCompatible + DowncastRefFromAny + 'static> ArgType for T {
391        fn check(value: AnyView<'_>) -> bool {
392            value.downcast_ref::<T>().is_some()
393        }
394
395        fn type_str() -> std::string::String {
396            T::type_str()
397        }
398
399        fn mismatch(value: AnyView<'_>) -> std::string::String {
400            T::get_mismatch_type_info(value.as_raw_ffi_any())
401        }
402    }
403
404    /// The typed expressions, which are argument types as they are: [`PrimVar`] accepts a [`Var`]
405    /// whose type is a `PrimType`.
406    pub use crate::ir::expr::{IntExpr, PrimExpr, PrimVar};
407
408    /// Return whether `value` is a [`Var`], not a subclass, whose type is an `N`, such as
409    /// `TensorTypeObj`: the check of variable argument types such as
410    /// [`TensorVar`](crate::tirx::TensorVar).
411    pub fn var_of_type<N: ObjectCore>(value: AnyView<'_>) -> bool {
412        value.type_index() == VarObj::type_index()
413            && value
414                .downcast_ref::<VarObj>()
415                .is_some_and(|var| var.ty.downcast_ref::<N>().is_some())
416    }
417
418    /// Describe a required value argument `name` of type `T`, documented by `doc`; [`Expr`]
419    /// accepts any.
420    pub fn arg<T: ArgType>(name: &str, doc: &str) -> Arg<T> {
421        Arg { name: String::from(name), doc: String::from(doc), ty: PhantomData }
422    }
423
424    /// Describe zero or more further value arguments `name` of type `T`, documented by `doc`; a
425    /// signature has at most one variadic value tail.
426    pub fn var_args<T: ArgType>(name: &str, doc: &str) -> VarArgs<T> {
427        VarArgs { name: String::from(name), doc: String::from(doc), ty: PhantomData }
428    }
429
430    /// Describe a required type argument `name` of type `T`, documented by `doc`; [`Type`] accepts
431    /// any.
432    pub fn ty_arg<T: ArgType>(name: &str, doc: &str) -> TyArg<T> {
433        TyArg { name: String::from(name), doc: String::from(doc), ty: PhantomData }
434    }
435
436    /// Describe zero or more further type arguments `name` of type `T`, documented by `doc`; a
437    /// signature has at most one variadic type-argument tail.
438    pub fn var_ty_args<T: ArgType>(name: &str, doc: &str) -> VarTyArgs<T> {
439        VarTyArgs { name: String::from(name), doc: String::from(doc), ty: PhantomData }
440    }
441
442    /// Describe the attributes of a Call: `Call.attrs` holds a `T`, which is also the operator's
443    /// attrs type; a signature has at most one.
444    pub fn call_attrs<T>() -> CallAttrs<T>
445    where
446        T: ObjectRefCore + Into<Attrs> + 'static,
447    {
448        CallAttrs { ty: PhantomData }
449    }
450
451    /// A descriptor of a required value argument of type `T`, made by [`arg`].
452    pub struct Arg<T> {
453        name: String,
454        doc: String,
455        ty: PhantomData<fn() -> T>,
456    }
457
458    /// A descriptor of a variadic value tail of type `T`, made by [`var_args`].
459    pub struct VarArgs<T> {
460        name: String,
461        doc: String,
462        ty: PhantomData<fn() -> T>,
463    }
464
465    /// A descriptor of a required type argument of type `T`, made by [`ty_arg`].
466    pub struct TyArg<T> {
467        name: String,
468        doc: String,
469        ty: PhantomData<fn() -> T>,
470    }
471
472    /// A descriptor of a variadic type-argument tail of type `T`, made by [`var_ty_args`].
473    pub struct VarTyArgs<T> {
474        name: String,
475        doc: String,
476        ty: PhantomData<fn() -> T>,
477    }
478
479    /// A descriptor of `Call.attrs` of type `T`, made by [`call_attrs`].
480    pub struct CallAttrs<T> {
481        ty: PhantomData<fn() -> T>,
482    }
483
484    /// The argument descriptions a signature gives its operator.
485    #[doc(hidden)]
486    #[derive(Default)]
487    pub struct Description {
488        arg_names: Vec<String>,
489        arg_docs: Vec<String>,
490        ty_arg_names: Vec<String>,
491        ty_arg_docs: Vec<String>,
492        /// Empty, or the tail's name and documentation.
493        var_args: Vec<String>,
494        var_ty_args: Vec<String>,
495    }
496
497    impl Description {
498        /// The lists `ir.Op._set_signature` takes.
499        pub(super) fn into_lists(self) -> [Vec<String>; 6] {
500            let Self { arg_names, arg_docs, ty_arg_names, ty_arg_docs, var_args, var_ty_args } =
501                self;
502            [arg_names, arg_docs, ty_arg_names, ty_arg_docs, var_args, var_ty_args]
503        }
504    }
505
506    /// One descriptor of a signature: what it adds to the description, and what it checks.
507    #[doc(hidden)]
508    pub trait Descriptor: 'static {
509        const ARGS: usize = 0;
510        const TY_ARGS: usize = 0;
511        const VAR_ARGS: usize = 0;
512        const VAR_TY_ARGS: usize = 0;
513        const CALL_ATTRS: usize = 0;
514        /// The type key of the attrs type, if the descriptor names one.
515        const ATTRS_TYPE_KEY: Option<&'static str> = None;
516
517        fn describe(self, description: &mut Description);
518
519        /// Check what this describes of `call`. `fixed` counts the signature's fixed value and
520        /// type arguments, where its tails start, and `at` those declared before this one.
521        fn check(
522            call: &CallObj,
523            op: &OpObj,
524            fixed: (usize, usize),
525            at: (usize, usize),
526        ) -> Result<()>;
527    }
528
529    impl<T: ArgType> Descriptor for Arg<T> {
530        const ARGS: usize = 1;
531
532        fn describe(self, description: &mut Description) {
533            description.arg_names.push(self.name);
534            description.arg_docs.push(self.doc);
535        }
536
537        fn check(call: &CallObj, op: &OpObj, _: (usize, usize), at: (usize, usize)) -> Result<()> {
538            check_value::<T, Expr>(op, false, || AnyView::from(&call.args[at.0]), at.0)
539        }
540    }
541
542    impl<T: ArgType> Descriptor for VarArgs<T> {
543        const VAR_ARGS: usize = 1;
544
545        fn describe(self, description: &mut Description) {
546            description.var_args = vec![self.name, self.doc];
547        }
548
549        fn check(
550            call: &CallObj,
551            op: &OpObj,
552            fixed: (usize, usize),
553            _: (usize, usize),
554        ) -> Result<()> {
555            (fixed.0..call.args.len()).try_for_each(|i| {
556                check_value::<T, Expr>(op, false, || AnyView::from(&call.args[i]), i)
557            })
558        }
559    }
560
561    impl<T: ArgType> Descriptor for TyArg<T> {
562        const TY_ARGS: usize = 1;
563
564        fn describe(self, description: &mut Description) {
565            description.ty_arg_names.push(self.name);
566            description.ty_arg_docs.push(self.doc);
567        }
568
569        fn check(call: &CallObj, op: &OpObj, _: (usize, usize), at: (usize, usize)) -> Result<()> {
570            check_value::<T, Type>(op, true, || AnyView::from(&call.ty_args[at.1]), at.1)
571        }
572    }
573
574    impl<T: ArgType> Descriptor for VarTyArgs<T> {
575        const VAR_TY_ARGS: usize = 1;
576
577        fn describe(self, description: &mut Description) {
578            description.var_ty_args = vec![self.name, self.doc];
579        }
580
581        fn check(
582            call: &CallObj,
583            op: &OpObj,
584            fixed: (usize, usize),
585            _: (usize, usize),
586        ) -> Result<()> {
587            (fixed.1..call.ty_args.len()).try_for_each(|i| {
588                check_value::<T, Type>(op, true, || AnyView::from(&call.ty_args[i]), i)
589            })
590        }
591    }
592
593    impl<T: ObjectRefCore + 'static> Descriptor for CallAttrs<T> {
594        const CALL_ATTRS: usize = 1;
595        const ATTRS_TYPE_KEY: Option<&'static str> = Some(T::ContainerType::TYPE_KEY);
596
597        fn describe(self, _: &mut Description) {}
598
599        fn check(call: &CallObj, op: &OpObj, _: (usize, usize), _: (usize, usize)) -> Result<()> {
600            let actual = match &call.attrs {
601                Some(attrs) if attrs.downcast_ref::<T::ContainerType>().is_some() => return Ok(()),
602                Some(attrs) => {
603                    format!(
604                        "`{}`",
605                        tvm_ffi::reflection::type_key(AnyView::from(attrs).type_index())
606                            .unwrap_or_default()
607                    )
608                }
609                None => "None".into(),
610            };
611            Err(tvm_ffi::format_err!(
612                TYPE_ERROR,
613                "Op `{}`: Call.attrs expected `{}`, got {actual}",
614                op.name.as_str(),
615                T::ContainerType::TYPE_KEY,
616            ))
617        }
618    }
619
620    /// The checks of a signature, as a list of descriptors in declaration order.
621    #[doc(hidden)]
622    pub trait Checks: 'static {
623        const ARGS: usize;
624        const TY_ARGS: usize;
625        const VAR_ARGS: usize;
626        const VAR_TY_ARGS: usize;
627        const CALL_ATTRS: usize;
628        const ATTRS_TYPE_KEY: Option<&'static str>;
629
630        /// Check the arguments of `call` these descriptors describe, in declaration order, as
631        /// [`Descriptor::check`] does.
632        fn check(
633            call: &CallObj,
634            op: &OpObj,
635            fixed: (usize, usize),
636            at: (usize, usize),
637        ) -> Result<()>;
638    }
639
640    impl Checks for () {
641        const ARGS: usize = 0;
642        const TY_ARGS: usize = 0;
643        const VAR_ARGS: usize = 0;
644        const VAR_TY_ARGS: usize = 0;
645        const CALL_ATTRS: usize = 0;
646        const ATTRS_TYPE_KEY: Option<&'static str> = None;
647
648        fn check(_: &CallObj, _: &OpObj, _: (usize, usize), _: (usize, usize)) -> Result<()> {
649            Ok(())
650        }
651    }
652
653    impl<D: Descriptor, L: Checks> Checks for (D, L) {
654        const ARGS: usize = D::ARGS + L::ARGS;
655        const TY_ARGS: usize = D::TY_ARGS + L::TY_ARGS;
656        const VAR_ARGS: usize = D::VAR_ARGS + L::VAR_ARGS;
657        const VAR_TY_ARGS: usize = D::VAR_TY_ARGS + L::VAR_TY_ARGS;
658        const CALL_ATTRS: usize = D::CALL_ATTRS + L::CALL_ATTRS;
659        const ATTRS_TYPE_KEY: Option<&'static str> = match D::ATTRS_TYPE_KEY {
660            Some(key) => Some(key),
661            None => L::ATTRS_TYPE_KEY,
662        };
663
664        fn check(
665            call: &CallObj,
666            op: &OpObj,
667            fixed: (usize, usize),
668            at: (usize, usize),
669        ) -> Result<()> {
670            D::check(call, op, fixed, at)?;
671            L::check(call, op, fixed, (at.0 + D::ARGS, at.1 + D::TY_ARGS))
672        }
673    }
674
675    /// The descriptors that [`OpDef::signature`] takes: a descriptor, or a tuple of them in order.
676    ///
677    /// `()` declares no argument.
678    pub trait Specs {
679        #[doc(hidden)]
680        type Checks: Checks;
681
682        #[doc(hidden)]
683        fn describe(self, description: &mut Description);
684    }
685
686    impl<D: Descriptor> Specs for D {
687        type Checks = (D, ());
688
689        fn describe(self, description: &mut Description) {
690            Descriptor::describe(self, description);
691        }
692    }
693
694    /// `Specs` of the tuples of descriptors, whose checks nest in declaration order.
695    macro_rules! tuple_specs {
696        (@nest) => { () };
697        (@nest $head:ident $(, $rest:ident)*) => { ($head, tuple_specs!(@nest $($rest),*)) };
698        ($($name:ident),*) => {
699            impl<$($name: Descriptor),*> Specs for ($($name,)*) {
700                type Checks = tuple_specs!(@nest $($name),*);
701
702                #[allow(non_snake_case, unused_variables)]
703                fn describe(self, description: &mut Description) {
704                    let ($($name,)*) = self;
705                    $(Descriptor::describe($name, description);)*
706                }
707            }
708        };
709    }
710
711    tuple_specs!();
712    tuple_specs!(A);
713    tuple_specs!(A, B);
714    tuple_specs!(A, B, C);
715    tuple_specs!(A, B, C, D);
716    tuple_specs!(A, B, C, D, E);
717    tuple_specs!(A, B, C, D, E, F);
718    tuple_specs!(A, B, C, D, E, F, G);
719    tuple_specs!(A, B, C, D, E, F, G, H);
720    tuple_specs!(A, B, C, D, E, F, G, H, I);
721    tuple_specs!(A, B, C, D, E, F, G, H, I, J);
722    tuple_specs!(A, B, C, D, E, F, G, H, I, J, K);
723    tuple_specs!(A, B, C, D, E, F, G, H, I, J, K, L);
724
725    /// Check `call` against the signature `L`: the argument counts, then each argument's type and
726    /// the attrs, in declaration order.
727    pub(super) fn validate<L: Checks>(call: &CallObj) -> Result<()> {
728        const {
729            assert!(
730                L::VAR_ARGS <= 1 && L::VAR_TY_ARGS <= 1 && L::CALL_ATTRS <= 1,
731                "a signature has at most one variadic tail of each kind and one call_attrs"
732            )
733        };
734        let Some(op) = call.op.downcast_ref::<OpObj>() else {
735            return Err(Error::new(TYPE_ERROR, "Invalid Op Call"));
736        };
737        let count = |label: &str, expected: usize, tail: bool, unit: &str, got: usize| {
738            let short = if tail { got < expected } else { got != expected };
739            if !short {
740                return Ok(());
741            }
742            let at_least = if tail { "at least " } else { "" };
743            let plural = if expected == 1 { "" } else { "s" };
744            Err(tvm_ffi::format_err!(
745                TYPE_ERROR,
746                "Op `{}`: {label} expected {at_least}{expected} {unit}{plural}, got {got}",
747                op.name.as_str()
748            ))
749        };
750        count("Call.args", L::ARGS, L::VAR_ARGS == 1, "argument", call.args.len())?;
751        count(
752            "Call.ty_args",
753            L::TY_ARGS,
754            L::VAR_TY_ARGS == 1,
755            "type argument",
756            call.ty_args.len(),
757        )?;
758        L::check(call, op, (L::ARGS, L::TY_ARGS), (0, 0))
759    }
760
761    /// Check argument `index` against `T`. `Base` is the category's base type, which accepts any
762    /// value unchecked.
763    fn check_value<'a, T: ArgType, Base: 'static>(
764        op: &OpObj,
765        type_arg: bool,
766        value: impl FnOnce() -> AnyView<'a>,
767        index: usize,
768    ) -> Result<()> {
769        if TypeId::of::<T>() == TypeId::of::<Base>() {
770            return Ok(());
771        }
772        // Borrowed in place: indexing an `Array` bumps no reference count.
773        let value = value();
774        if !value.is_none() && T::check(value) {
775            return Ok(());
776        }
777        let (fixed, tail) = match type_arg {
778            false => (&op.args_info, &op.var_args_info),
779            true => (&op.ty_args_info, &op.var_ty_args_info),
780        };
781        let name = match fixed.get(index) {
782            Some(info) => Some(info.name.clone()),
783            None => tail.as_ref().map(|info| info.name.clone()),
784        };
785        let name = match name {
786            Some(name) if !name.as_str().is_empty() => format!(" (`{}`)", name.as_str()),
787            _ => std::string::String::new(),
788        };
789        Err(tvm_ffi::format_err!(
790            TYPE_ERROR,
791            "Op `{}`: `{}[{index}]`{name} expected `{}`, got `{}`.",
792            op.name.as_str(),
793            if type_arg { "Call.ty_args" } else { "Call.args" },
794            T::type_str(),
795            T::mismatch(value),
796        ))
797    }
798}
799
800// ---------------------------------------------------------------------------------------------
801// Helpers
802
803/// Request the APIs of a defined operator in registered destinations through `ir.expose_op`,
804/// after its signature and attributes are ready. An absent receiver is a no-op; an installed
805/// receiver's error is returned.
806fn complete(state: Result<Op>) -> Result<Op> {
807    let op = state?;
808    if let Ok(expose) = tvm_ffi::Function::get_global("ir.expose_op") {
809        expose.call_tuple((op.name.clone(),))?;
810    }
811    Ok(op)
812}
813
814/// The text of `doc` without the indentation its lines share and without the blank lines around
815/// it. Text that is not indented is unchanged.
816fn doc_text(doc: &str) -> std::string::String {
817    let indent = doc
818        .lines()
819        .filter(|line| !line.trim().is_empty())
820        .map(|line| line.len() - line.trim_start().len())
821        .min()
822        .unwrap_or(0);
823    let lines: Vec<&str> =
824        doc.lines().map(|line| line.get(indent..).unwrap_or("").trim_end()).collect();
825    lines.join("\n").trim().to_string()
826}