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