melior/ir/block/
argument.rs1use super::Value;
2use crate::{
3 ir::{BlockRef, Type, TypeLike, ValueLike},
4 Error,
5};
6use mlir_sys::{
7 mlirBlockArgumentGetArgNumber, mlirBlockArgumentGetOwner, mlirBlockArgumentSetType, MlirValue,
8};
9use std::fmt::{self, Display, Formatter};
10
11#[derive(Clone, Copy, Debug)]
13pub struct BlockArgument<'c, 'a> {
14 value: Value<'c, 'a>,
15}
16
17impl<'c> BlockArgument<'c, '_> {
18 pub fn argument_number(&self) -> usize {
20 unsafe { mlirBlockArgumentGetArgNumber(self.value.to_raw()) as usize }
21 }
22
23 pub fn owner(&self) -> BlockRef<'c, '_> {
25 unsafe { BlockRef::from_raw(mlirBlockArgumentGetOwner(self.value.to_raw())) }
26 }
27
28 pub fn set_type(&self, r#type: Type) {
30 unsafe { mlirBlockArgumentSetType(self.value.to_raw(), r#type.to_raw()) }
31 }
32
33 pub unsafe fn from_raw(value: MlirValue) -> Self {
39 Self {
40 value: Value::from_raw(value),
41 }
42 }
43}
44
45impl<'c> ValueLike<'c> for BlockArgument<'c, '_> {
46 fn to_raw(&self) -> MlirValue {
47 self.value.to_raw()
48 }
49}
50
51impl Display for BlockArgument<'_, '_> {
52 fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
53 Value::from(*self).fmt(formatter)
54 }
55}
56
57impl<'c, 'a> TryFrom<Value<'c, 'a>> for BlockArgument<'c, 'a> {
58 type Error = Error;
59
60 fn try_from(value: Value<'c, 'a>) -> Result<Self, Self::Error> {
61 if value.is_block_argument() {
62 Ok(Self { value })
63 } else {
64 Err(Error::BlockArgumentExpected(value.to_string()))
65 }
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72 use crate::{
73 context::Context,
74 ir::{Block, Location},
75 };
76
77 #[test]
78 fn argument_number() {
79 let context = Context::new();
80 let r#type = Type::parse(&context, "index").unwrap();
81 let block = Block::new(&[(r#type, Location::unknown(&context))]);
82
83 assert_eq!(block.argument(0).unwrap().argument_number(), 0);
84 }
85
86 #[test]
87 fn owner() {
88 let context = Context::new();
89 let r#type = Type::parse(&context, "index").unwrap();
90 let block = Block::new(&[(r#type, Location::unknown(&context))]);
91
92 assert_eq!(&*block.argument(0).unwrap().owner(), &block);
93 }
94
95 #[test]
96 fn set_type() {
97 let context = Context::new();
98 let r#type = Type::parse(&context, "index").unwrap();
99 let other_type = Type::parse(&context, "f64").unwrap();
100 let block = Block::new(&[(r#type, Location::unknown(&context))]);
101 let argument = block.argument(0).unwrap();
102
103 argument.set_type(other_type);
104
105 assert_eq!(argument.r#type(), other_type);
106 }
107}