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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
//! Constant and specialization constant representations.
use std::convert::TryFrom;

use ordered_float::OrderedFloat;

use crate::{
    error::{anyhow, Result},
    ty::{ScalarType, Type},
    var::SpecId,
};

/// Typed constant value.
#[non_exhaustive]
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub enum ConstantValue {
    Typeless(Box<[u8]>),
    Bool(bool),
    S32(i32),
    U32(u32),
    F32(OrderedFloat<f32>),
}
impl From<&[u32]> for ConstantValue {
    fn from(x: &[u32]) -> Self {
        let bytes = x.iter().flat_map(|x| x.to_ne_bytes()).collect();
        ConstantValue::Typeless(bytes)
    }
}
impl From<&[u8]> for ConstantValue {
    fn from(x: &[u8]) -> Self {
        let bytes = x.to_owned().into_boxed_slice();
        ConstantValue::Typeless(bytes)
    }
}
impl From<[u8; 4]> for ConstantValue {
    fn from(x: [u8; 4]) -> Self {
        ConstantValue::try_from(&x as &[u8]).unwrap()
    }
}
impl From<[u8; 8]> for ConstantValue {
    fn from(x: [u8; 8]) -> Self {
        ConstantValue::try_from(&x as &[u8]).unwrap()
    }
}
impl From<bool> for ConstantValue {
    fn from(x: bool) -> Self {
        Self::Bool(x)
    }
}
impl From<u32> for ConstantValue {
    fn from(x: u32) -> Self {
        Self::U32(x)
    }
}
impl From<i32> for ConstantValue {
    fn from(x: i32) -> Self {
        Self::S32(x)
    }
}
impl From<f32> for ConstantValue {
    fn from(x: f32) -> Self {
        Self::F32(OrderedFloat(x))
    }
}
impl ConstantValue {
    pub fn to_typed(&self, ty: &Type) -> Result<Self> {
        let x = match self {
            Self::Typeless(x) => x,
            _ => return Err(anyhow!("{self:?} is already typed")),
        };

        if let Some(scalar_ty) = ty.as_scalar() {
            match scalar_ty {
                ScalarType::Boolean => Ok(ConstantValue::Bool(x.iter().any(|x| x != &0))),
                ScalarType::Integer {
                    bits: 32,
                    is_signed: true,
                } if x.len() == 4 => {
                    let x = i32::from_ne_bytes([x[0], x[1], x[2], x[3]]);
                    Ok(ConstantValue::S32(x))
                }
                ScalarType::Integer {
                    bits: 32,
                    is_signed: false,
                } if x.len() == 4 => {
                    let x = u32::from_ne_bytes([x[0], x[1], x[2], x[3]]);
                    Ok(ConstantValue::U32(x))
                }
                ScalarType::Float { bits: 32 } if x.len() == 4 => {
                    let x = f32::from_ne_bytes([x[0], x[1], x[2], x[3]]);
                    Ok(ConstantValue::F32(OrderedFloat(x)))
                }
                _ => Err(anyhow!(
                    "cannot parse {:?} from {} bytes",
                    scalar_ty,
                    x.len()
                )),
            }
        } else {
            Err(anyhow!("cannot parse {:?} as a constant value", ty))
        }
    }

    pub fn to_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(x) => Some(*x),
            _ => None,
        }
    }
    pub fn to_s32(&self) -> Option<i32> {
        match self {
            Self::S32(x) => Some(*x),
            _ => None,
        }
    }
    pub fn to_u32(&self) -> Option<i32> {
        match self {
            Self::S32(x) => Some(*x),
            _ => None,
        }
    }
    pub fn to_f32(&self) -> Option<f32> {
        match self {
            Self::F32(x) => Some((*x).into()),
            _ => None,
        }
    }
}

/// Constant or specialization constant record.
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub struct Constant {
    pub name: Option<String>,
    /// Type of constant.
    pub ty: Type,
    /// Defined value of constant, or default value of specialization constant.
    pub value: ConstantValue,
    /// Specialization constant ID, notice that this is NOT an instruction ID.
    /// It is used to identify specialization constants for graphics libraries.
    pub spec_id: Option<SpecId>,
}
impl Constant {
    /// Create a constant record with name, type and value. `ty` must be a
    /// `ScalarType`.
    pub fn new(name: Option<String>, ty: Type, value: ConstantValue) -> Self {
        Self {
            name,
            ty,
            value,
            spec_id: None,
        }
    }
    /// Create an intermediate constant record with type and value. Intermediate
    /// constants don't have names because they contribute to subexpressions in
    /// arithmetic.
    pub fn new_itm(ty: Type, value: ConstantValue) -> Self {
        Self {
            name: None,
            ty,
            value,
            spec_id: None,
        }
    }
    /// Create a specialization constant record with name, type, default value
    /// and a `SpecId`.
    pub fn new_spec(name: Option<String>, ty: Type, value: ConstantValue, spec_id: SpecId) -> Self {
        Self {
            name,
            ty,
            value: value,
            spec_id: Some(spec_id),
        }
    }
}