1use serde::Serialize;
13
14use crate::ast::PrimitiveType;
15use crate::base::{self, ConstId, IdVec, MrId, StructId, TypeRef};
16use crate::rast::Env;
17use crate::ty::value::ConstValue;
18use crate::ty::width::{width, Width};
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
22pub enum Ty {
23 Prim(PrimitiveType),
25 Addr(Option<MrId>),
27 Struct(StructId),
29 Array {
31 elem: Box<Ty>,
33 len: ArrayLen,
35 },
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
40pub struct ArrayLen {
41 pub len: u64,
43 pub written: Option<ConstId>,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
49pub struct FfnSig {
50 pub params: Vec<Ty>,
52 pub ret: Option<Ty>,
54 pub variadic: bool,
56}
57
58pub(super) type Values = IdVec<ConstId, Option<ConstValue>>;
60
61impl Ty {
62 pub const BOOL: Ty = Ty::Prim(PrimitiveType::Bool);
64 pub const INT: Ty = Ty::Prim(PrimitiveType::Int64);
66 pub const UINT: Ty = Ty::Prim(PrimitiveType::UInt64);
68
69 #[must_use]
71 pub fn is_subtype(&self, other: &Ty) -> bool {
72 self == other || matches!((self, other), (Ty::Addr(Some(_)), Ty::Addr(None)))
73 }
74
75 #[must_use]
77 pub fn integer(&self) -> Option<PrimitiveType> {
78 match self {
79 Ty::Prim(p) if *p != PrimitiveType::Bool => Some(*p),
80 _ => None,
81 }
82 }
83
84 #[must_use]
87 pub(crate) fn width(&self) -> Option<&'static dyn Width> {
88 match self {
89 Ty::Prim(p) => width(*p),
90 Ty::Addr(_) => width(PrimitiveType::Address),
91 Ty::Struct(_) | Ty::Array { .. } => None,
92 }
93 }
94
95 pub(super) fn fits_i64(&self, v: i64, env: &Env) -> Result<(), String> {
102 match self.width() {
103 Some(w) if w.signed(v).is_none() => Err(self.out_of_range(&v, w, env)),
104 _ => Ok(()),
105 }
106 }
107
108 pub(super) fn fits_u64(&self, v: u64, env: &Env) -> Result<(), String> {
114 match self.width() {
115 Some(w) if w.unsigned(v).is_none() => Err(self.out_of_range(&v, w, env)),
116 _ => Ok(()),
117 }
118 }
119
120 fn out_of_range(&self, v: &dyn std::fmt::Display, w: &dyn Width, env: &Env) -> String {
121 let (lo, hi) = w.bounds();
122 format!(
123 "value {v} is out of range for {} ({lo}..={hi})",
124 self.display(env)
125 )
126 }
127
128 #[must_use]
130 pub fn display(&self, env: &Env) -> String {
131 match self {
132 Ty::Prim(p) => p.to_string(),
133 Ty::Addr(None) => "Address".to_owned(),
134 Ty::Addr(Some(m)) => format!("Addr({})", env.mrs[*m].name),
135 Ty::Struct(r) => env.structs[*r].name.clone(),
136 Ty::Array { elem, len } => format!("{}[{}]", elem.display(env), len.len),
137 }
138 }
139}
140
141pub(super) fn prim(p: PrimitiveType) -> Ty {
143 match p {
144 PrimitiveType::Int => Ty::Prim(PrimitiveType::Int64),
145 PrimitiveType::UInt => Ty::Prim(PrimitiveType::UInt64),
146 PrimitiveType::Byte => Ty::Prim(PrimitiveType::UInt8),
147 PrimitiveType::Address => Ty::Addr(None),
148 p => Ty::Prim(p),
149 }
150}
151
152pub(super) fn lower(t: &TypeRef, consts: &Values, env: &Env) -> Result<Ty, String> {
158 Ok(match t {
159 TypeRef::Prim(p) => prim(*p),
160 TypeRef::Struct(r) => Ty::Struct(*r),
161 TypeRef::Array { elem, len } => Ty::Array {
162 elem: Box::new(lower(elem, consts, env)?),
163 len: array_len(len, consts, env)?,
164 },
165 })
166}
167
168pub(super) fn array_len(
175 len: &base::ArrayLen,
176 consts: &Values,
177 env: &Env,
178) -> Result<ArrayLen, String> {
179 match len {
180 base::ArrayLen::Lit(n) => Ok(ArrayLen {
181 len: *n,
182 written: None,
183 }),
184 base::ArrayLen::Const(id) => {
185 let name = &env.consts[*id].name;
186 match consts.get(*id).copied().flatten() {
187 Some(ConstValue::Bool(_)) => {
188 Err(format!("array length '{name}' is a bool, not an integer"))
189 }
190 Some(v) => v
191 .count()
192 .map(|len| ArrayLen {
193 len,
194 written: Some(*id),
195 })
196 .ok_or_else(|| format!("array length '{name}' is not a count ({v})")),
197 None => Err(format!(
198 "array length '{name}' is not a declared constant (declare it before the array)"
199 )),
200 }
201 }
202 }
203}
204
205pub(super) fn size_of(
213 t: &TypeRef,
214 consts: &Values,
215 env: &Env,
216 structs: &dyn Fn(StructId) -> Result<u64, String>,
217) -> Result<u64, String> {
218 match t {
219 TypeRef::Prim(p) => p.size_bytes().map(|n| n as u64).ok_or_else(|| {
220 format!("'{p}' has no fixed size \u{2014} use a sized type (e.g. int32, not int)")
221 }),
222 TypeRef::Struct(r) => structs(*r),
223 TypeRef::Array { elem, len } => {
224 let len = array_len(len, consts, env)?.len;
225 let elem = size_of(elem, consts, env, structs)?;
226 len.checked_mul(elem)
227 .ok_or_else(|| "array size overflows".to_owned())
228 }
229 }
230}
231
232pub(super) fn align_of(
235 t: &TypeRef,
236 structs: &dyn Fn(StructId) -> Result<u64, String>,
237) -> Result<u64, String> {
238 match t {
239 TypeRef::Prim(p) => p.size_bytes().map(|n| n as u64).ok_or_else(|| {
240 format!("'{p}' has no fixed size \u{2014} use a sized type (e.g. int32, not int)")
241 }),
242 TypeRef::Struct(r) => structs(*r),
243 TypeRef::Array { elem, .. } => align_of(elem, structs),
244 }
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250 use crate::base::Idx;
251
252 const FIS: &str = "struct Slot { tag: byte; }
253 const N: uint32 = 4;
254 const NEG: int = -1;
255 const FLAG: bool = true;
256 MemoryRegion ring(0x1000);
257 ProtectionDomain a(10);";
258
259 fn env() -> Env {
260 crate::rast::env::built(FIS, &[]).expect("resolves").0.env
261 }
262
263 fn values() -> Values {
264 [
265 Some(ConstValue::UInt32(4)),
266 Some(ConstValue::Int64(-1)),
267 Some(ConstValue::Bool(true)),
268 ]
269 .into_iter()
270 .collect()
271 }
272
273 #[test]
274 fn the_int_aliases_are_sized_and_address_is_addr() {
275 let env = env();
276 for (written, ty) in [
277 (PrimitiveType::Int, Ty::Prim(PrimitiveType::Int64)),
278 (PrimitiveType::UInt, Ty::Prim(PrimitiveType::UInt64)),
279 (PrimitiveType::Byte, Ty::Prim(PrimitiveType::UInt8)),
280 (PrimitiveType::Int32, Ty::Prim(PrimitiveType::Int32)),
281 (PrimitiveType::Address, Ty::Addr(None)),
282 ] {
283 assert_eq!(lower(&TypeRef::Prim(written), &values(), &env), Ok(ty));
284 }
285 }
286
287 #[test]
288 fn an_array_length_is_folded_and_keeps_its_const() {
289 let env = env();
290 let array = |len| TypeRef::Array {
291 elem: Box::new(TypeRef::Prim(PrimitiveType::Byte)),
292 len,
293 };
294 assert_eq!(
295 lower(
296 &array(base::ArrayLen::Const(ConstId::new(0))),
297 &values(),
298 &env
299 ),
300 Ok(Ty::Array {
301 elem: Box::new(Ty::Prim(PrimitiveType::UInt8)),
302 len: ArrayLen {
303 len: 4,
304 written: Some(ConstId::new(0)),
305 },
306 })
307 );
308 for (id, needle) in [(1, "is not a count (-1)"), (2, "is a bool, not an integer")] {
309 let err = lower(
310 &array(base::ArrayLen::Const(ConstId::new(id))),
311 &values(),
312 &env,
313 )
314 .unwrap_err();
315 assert!(err.contains(needle), "{err}");
316 }
317 let err = lower(
319 &array(base::ArrayLen::Const(ConstId::new(0))),
320 &Values::new(),
321 &env,
322 )
323 .unwrap_err();
324 assert!(err.contains("declare it before the array"), "{err}");
325 }
326
327 #[test]
328 fn display_names_every_form() {
329 let env = env();
330 let cases = [
331 (Ty::Prim(PrimitiveType::Int64), "int64"),
332 (Ty::Addr(None), "Address"),
333 (Ty::Addr(Some(MrId::new(0))), "Addr(ring)"),
334 (Ty::Struct(StructId::new(0)), "Slot"),
335 (
336 Ty::Array {
337 elem: Box::new(Ty::Prim(PrimitiveType::UInt8)),
338 len: ArrayLen {
339 len: 16,
340 written: None,
341 },
342 },
343 "uint8[16]",
344 ),
345 ];
346 for (ty, text) in cases {
347 assert_eq!(ty.display(&env), text);
348 }
349 }
350
351 #[test]
352 fn an_address_into_a_region_is_a_subtype_of_address() {
353 let refined = Ty::Addr(Some(MrId::new(0)));
354 assert!(refined.is_subtype(&Ty::Addr(None)));
355 assert!(!Ty::Addr(None).is_subtype(&refined));
356 assert!(!refined.is_subtype(&Ty::Prim(PrimitiveType::Int64)));
357 assert!(refined.is_subtype(&refined));
358 assert_eq!(
359 Ty::Prim(PrimitiveType::UInt8).integer(),
360 Some(PrimitiveType::UInt8)
361 );
362 assert_eq!(Ty::BOOL.integer(), None);
363 assert_eq!(Ty::Addr(None).integer(), None);
364 }
365}