1use 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
37pub struct OpDef(Option<Result<Op>>);
77
78impl OpDef {
79 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 pub fn op(mut self) -> Result<Op> {
96 complete(self.take())
97 }
98
99 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 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 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 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 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 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 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 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 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 self.attr("FInferType", unsafe { hook.into_any() }, false)
177 }
178
179 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 op.write_validator(unsafe { hook.into_any() }, true);
199 Ok(())
200 })
201 }
202
203 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 self.attr("FRegionGetBodyParams", unsafe { hook.into_any() }, false)
216 }
217
218 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 self.attr("FRegionValidate", unsafe { hook.into_any() }, false)
230 }
231
232 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 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 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 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
284pub struct AttrKey<T> {
289 name: &'static str,
290 value: PhantomData<fn() -> T>,
291}
292
293impl<T> AttrKey<T> {
294 pub const fn new(name: &'static str) -> Self {
296 Self { name, value: PhantomData }
297 }
298
299 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
313pub mod op_attr {
315 use super::{AttrKey, CallEffectKind};
316 use crate::ir::r#type::Type;
317
318 pub const CALL_EFFECT_KIND: AttrKey<CallEffectKind> = AttrKey::new("TCallEffectKind");
320 pub const FIXED_RETURN_TYPE: AttrKey<Type> = AttrKey::new("TFixedReturnType");
323}
324
325#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
327#[repr(i64)]
328pub enum CallEffectKind {
329 ExprAnnotation = 0,
331 Pure = 1,
333 ReadState = 2,
335 UpdateState = 3,
338 SpecialCallArg = 4,
341 EmbedInfo = 5,
343 ControlJump = 6,
345}
346
347impl CallEffectKind {
348 #[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
360pub 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 pub trait ArgType: 'static {
378 fn check(value: AnyView<'_>) -> bool;
380 fn type_str() -> std::string::String;
382 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 pub use crate::ir::expr::{IntExpr, PrimExpr, PrimVar};
407
408 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 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 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 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 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 pub fn call_attrs<T>() -> CallAttrs<T>
445 where
446 T: ObjectRefCore + Into<Attrs> + 'static,
447 {
448 CallAttrs { ty: PhantomData }
449 }
450
451 pub struct Arg<T> {
453 name: String,
454 doc: String,
455 ty: PhantomData<fn() -> T>,
456 }
457
458 pub struct VarArgs<T> {
460 name: String,
461 doc: String,
462 ty: PhantomData<fn() -> T>,
463 }
464
465 pub struct TyArg<T> {
467 name: String,
468 doc: String,
469 ty: PhantomData<fn() -> T>,
470 }
471
472 pub struct VarTyArgs<T> {
474 name: String,
475 doc: String,
476 ty: PhantomData<fn() -> T>,
477 }
478
479 pub struct CallAttrs<T> {
481 ty: PhantomData<fn() -> T>,
482 }
483
484 #[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 var_args: Vec<String>,
494 var_ty_args: Vec<String>,
495 }
496
497 impl Description {
498 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 #[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 const ATTRS_TYPE_KEY: Option<&'static str> = None;
516
517 fn describe(self, description: &mut Description);
518
519 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 #[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 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 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 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 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 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 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
800fn 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
814fn 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}