fic/ast/types.rs
1//! Core data types for the Fiducia language.
2//!
3//! Defines addresses, page sizes, memory permissions, and the Fiducia type system
4//! (primitive types, pointers, structs).
5//!
6//! ## Page Sizes
7//!
8//! Memory region sizes and virtual addresses must be aligned to one of two page granularities
9//! (seL4 AArch64):
10//!
11//! | Literal | Size | Name |
12//! |-------------|-------|-------|
13//! | `0x1000` | 4 KiB | Small |
14//! | `0x200000` | 2 MiB | Large |
15//!
16//! The page size defaults to `0x1000` (4 KiB) if omitted.
17//!
18//! ## Memory Permissions
19//!
20//! Mappings take a permission string literal (case-insensitive, order-insensitive):
21//!
22//! | String | Access |
23//! |----------|-----------------|
24//! | `"r"` | Read-only |
25//! | `"rw"` | Read-write |
26//! | `"rx"` | Read-execute |
27//! | `"rwx"` | Read-write-execute |
28//! | `"x"` | Execute-only |
29//! | `"wx"` | Write-execute |
30//!
31//! Write-only (`"w"`) is rejected. Character order does not matter: `"wr"` equals `"rw"`.
32//!
33//! ## Variable Types
34//!
35//! Types are used in top-level variable declarations and process bodies.
36//!
37//! **Primitive types:**
38//!
39//! | Type | Width | Signed |
40//! |----------|--------|--------|
41//! | `int` | arbitrary | yes |
42//! | `int8` | 8-bit | yes |
43//! | `int16` | 16-bit | yes |
44//! | `int32` | 32-bit | yes |
45//! | `int64` | 64-bit | yes |
46//! | `uint` | arbitrary | no |
47//! | `uint8` | 8-bit | no |
48//! | `uint16` | 16-bit | no |
49//! | `uint32` | 32-bit | no |
50//! | `uint64` | 64-bit | no |
51//! | `bool` | 1-byte | — |
52//! | `byte` | 1-byte | no |
53//! | `Address`| platform-width | — |
54//!
55//! **Struct type:** any identifier not matching a primitive — e.g. `MyStruct`
56//!
57//! Pointer types (`ptr<T>`) are intentionally absent — all memory access goes
58//! through named, declared `Mapping`s.
59
60use serde::{Deserialize, Serialize, Serializer};
61use std::error::Error;
62use std::fmt::{self, Display, Formatter};
63
64// ============================================================================
65// Address Type
66// ============================================================================
67
68/// A 64-bit memory address, parsed from hex literals (e.g., `0x1000`).
69///
70/// Used for memory region sizes, physical addresses, and virtual addresses.
71///
72/// Always 64-bit to match seL4 Microkit targets. When the common data layer
73/// is implemented, add `From<Address> for usize` (Rust FFI) and expose as
74/// `uintptr_t` (C FFI).
75///
76/// ```
77/// use fic::ast::Address;
78///
79/// let addr = Address::new(0x1000);
80/// assert_eq!(addr.value(), 0x1000);
81/// assert_eq!(format!("{addr}"), "0x1000");
82/// ```
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
84pub struct Address(u64);
85
86impl Address {
87 /// Create a new address from a raw `u64` value.
88 pub fn new(value: u64) -> Self {
89 Address(value)
90 }
91
92 /// Return the raw `u64` value.
93 pub fn value(&self) -> u64 {
94 self.0
95 }
96
97 /// Check if the address is aligned to the given page size.
98 ///
99 /// ```
100 /// use fic::ast::{Address, PageSize};
101 ///
102 /// let aligned = Address::new(0x1000);
103 /// assert!(aligned.is_aligned(PageSize::Small));
104 ///
105 /// let unaligned = Address::new(0x1001);
106 /// assert!(!unaligned.is_aligned(PageSize::Small));
107 /// ```
108 pub fn is_aligned(&self, page_size: PageSize) -> bool {
109 self.0.is_multiple_of(page_size.value())
110 }
111
112 /// Format as hex with underscore grouping every 3 digits: `0x3_000_000`.
113 pub fn to_hex_grouped(&self) -> String {
114 let hex = format!("{:x}", self.0);
115 let chars: Vec<char> = hex.chars().collect();
116 let mut result = String::new();
117 for (i, ch) in chars.iter().enumerate() {
118 if i > 0 && (chars.len() - i).is_multiple_of(3) {
119 result.push('_');
120 }
121 result.push(*ch);
122 }
123 format!("0x{result}")
124 }
125}
126
127impl Serialize for Address {
128 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
129 serializer.serialize_str(&self.to_hex_grouped())
130 }
131}
132
133// ============================================================================
134// Page Size
135// ============================================================================
136
137/// Page sizes supported by seL4 on `AArch64`.
138///
139/// - `Small` = 4 KiB (`0x1000`)
140/// - `Large` = 2 MiB (`0x200000`)
141///
142/// ```
143/// use fic::ast::PageSize;
144///
145/// assert_eq!(PageSize::Small.value(), 0x1000);
146/// assert_eq!(PageSize::default(), PageSize::Small);
147/// ```
148#[repr(u64)]
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
150pub enum PageSize {
151 /// 4 KiB page.
152 #[default]
153 Small = 0x1000,
154 /// 2 MiB large page.
155 Large = 0x0020_0000,
156}
157
158impl PageSize {
159 /// Return the page size in bytes.
160 pub fn value(&self) -> u64 {
161 *self as u64
162 }
163}
164
165/// The address does not correspond to a valid [`PageSize`].
166#[derive(Debug, PartialEq)]
167pub struct InvalidPageSize;
168
169impl TryFrom<Address> for PageSize {
170 type Error = InvalidPageSize;
171
172 fn try_from(value: Address) -> Result<Self, Self::Error> {
173 match value.0 {
174 0x1000 => Ok(PageSize::Small),
175 0x0020_0000 => Ok(PageSize::Large),
176 _ => Err(InvalidPageSize),
177 }
178 }
179}
180
181// Allows: page == 0x1000
182impl PartialEq<u64> for PageSize {
183 fn eq(&self, other: &u64) -> bool {
184 self.value() == *other
185 }
186}
187
188// Allows: 0x1000 == page
189impl PartialEq<PageSize> for u64 {
190 fn eq(&self, other: &PageSize) -> bool {
191 *self == other.value()
192 }
193}
194
195impl PartialEq<Address> for PageSize {
196 fn eq(&self, other: &Address) -> bool {
197 self.value() == other.0
198 }
199}
200
201impl PartialEq<PageSize> for Address {
202 fn eq(&self, other: &PageSize) -> bool {
203 self.0 == other.value()
204 }
205}
206
207impl Display for PageSize {
208 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
209 match self {
210 PageSize::Small => write!(f, "4KiB"),
211 PageSize::Large => write!(f, "2MiB"),
212 }
213 }
214}
215
216impl PageSize {
217 /// Turns `PageSize` into a number as a string
218 pub fn to_string_number(&self) -> String {
219 match self {
220 PageSize::Small => "4096".to_string(),
221 PageSize::Large => "2097152".to_string(),
222 }
223 }
224}
225
226// ============================================================================
227// Permission
228// ============================================================================
229
230/// Memory access permissions for mappings.
231///
232/// Parsed from string literals like `"rw"`, `"rx"`, `"rwx"`.
233///
234/// ```
235/// use fic::ast::Permission;
236///
237/// let perm = Permission::from_str("rw").unwrap();
238/// assert_eq!(perm, Permission::RW);
239/// assert_eq!(perm.as_str(), "rw");
240/// ```
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
242pub enum Permission {
243 /// Read-only.
244 R,
245 /// Read-write.
246 RW,
247 /// Read-execute.
248 RX,
249 /// Read-write-execute.
250 RWX,
251 /// Execute-only.
252 X,
253 /// Write-execute.
254 WX,
255}
256
257impl Permission {
258 /// Parse a permission string (case-insensitive, order-insensitive).
259 ///
260 /// Characters are sorted before matching, so `"wr"` is equivalent to `"rw"`.
261 /// Write-only (`"w"`) is rejected — a read or execute permission is required.
262 pub fn from_str(s: &str) -> Result<Self, InvalidPermission> {
263 let mut chars: Vec<char> = s.to_lowercase().chars().collect();
264 chars.sort_unstable();
265 let sorted: String = chars.into_iter().collect();
266 match sorted.as_str() {
267 "r" => Ok(Permission::R),
268 "rw" => Ok(Permission::RW),
269 "rx" => Ok(Permission::RX),
270 "rwx" => Ok(Permission::RWX),
271 "x" => Ok(Permission::X),
272 "wx" => Ok(Permission::WX),
273 _ => Err(InvalidPermission(s.to_string())),
274 }
275 }
276
277 /// Return the canonical lowercase string representation.
278 pub fn as_str(&self) -> &'static str {
279 match self {
280 Permission::R => "r",
281 Permission::RW => "rw",
282 Permission::RX => "rx",
283 Permission::RWX => "rwx",
284 Permission::X => "x",
285 Permission::WX => "wx",
286 }
287 }
288
289 /// Return the Microkit integer representation.
290 pub fn as_int(&self) -> u8 {
291 match self {
292 Permission::R => 0b1,
293 Permission::RW => 0b11,
294 Permission::X => 0b100,
295 Permission::RX => 0b101,
296 Permission::WX => 0b110,
297 Permission::RWX => 0b111,
298 }
299 }
300}
301
302/// The string is not a [`Permission`].
303#[derive(Debug, PartialEq)]
304pub struct InvalidPermission(pub String);
305
306impl Display for InvalidPermission {
307 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
308 write!(
309 f,
310 "invalid permission '{}': a combination of r, w and x, not write-only",
311 self.0
312 )
313 }
314}
315
316impl Error for InvalidPermission {}
317
318impl Display for Permission {
319 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
320 write!(f, "{}", self.as_str())
321 }
322}
323
324impl Display for Address {
325 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
326 write!(f, "{:#x}", self.0)
327 }
328}
329
330impl fmt::LowerHex for Address {
331 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
332 fmt::LowerHex::fmt(&self.0, f)
333 }
334}
335
336impl From<u64> for Address {
337 fn from(value: u64) -> Self {
338 Address(value)
339 }
340}
341
342impl From<Address> for u64 {
343 fn from(addr: Address) -> Self {
344 addr.0
345 }
346}
347
348// ============================================================================
349// Variable Types
350// ============================================================================
351
352/// A primitive type in Fiducia.
353///
354/// Covers signed/unsigned integers of various widths, booleans, `byte`, and `Address`.
355#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
356pub enum PrimitiveType {
357 /// Alias of `int64`.
358 Int,
359 /// 8-bit signed integer.
360 Int8,
361 /// 16-bit signed integer.
362 Int16,
363 /// 32-bit signed integer.
364 Int32,
365 /// 64-bit signed integer.
366 Int64,
367 /// Alias of `uint64`.
368 UInt,
369 /// 8-bit unsigned integer.
370 UInt8,
371 /// 16-bit unsigned integer.
372 UInt16,
373 /// 32-bit unsigned integer.
374 UInt32,
375 /// 64-bit unsigned integer.
376 UInt64,
377 /// Boolean type.
378 Bool,
379 /// 8-bit unsigned byte (register values, single-byte flags).
380 Byte,
381 /// Platform-width virtual/physical address; arithmetic is defined on it.
382 Address,
383}
384
385impl PrimitiveType {
386 /// Get the size in bytes, or `None` for arbitrary-precision / platform-width types.
387 pub fn size_bytes(&self) -> Option<usize> {
388 match self {
389 PrimitiveType::Int8
390 | PrimitiveType::UInt8
391 | PrimitiveType::Bool
392 | PrimitiveType::Byte => Some(1),
393 PrimitiveType::Int16 | PrimitiveType::UInt16 => Some(2),
394 PrimitiveType::Int32 | PrimitiveType::UInt32 => Some(4),
395 PrimitiveType::Int64 | PrimitiveType::UInt64 => Some(8),
396 PrimitiveType::Int | PrimitiveType::UInt | PrimitiveType::Address => None,
397 }
398 }
399
400 /// Returns `true` if this is a signed integer type.
401 pub fn is_signed(&self) -> bool {
402 matches!(
403 self,
404 PrimitiveType::Int
405 | PrimitiveType::Int8
406 | PrimitiveType::Int16
407 | PrimitiveType::Int32
408 | PrimitiveType::Int64
409 )
410 }
411}
412
413impl Display for PrimitiveType {
414 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
415 match self {
416 PrimitiveType::Int => write!(f, "int"),
417 PrimitiveType::Int8 => write!(f, "int8"),
418 PrimitiveType::Int16 => write!(f, "int16"),
419 PrimitiveType::Int32 => write!(f, "int32"),
420 PrimitiveType::Int64 => write!(f, "int64"),
421 PrimitiveType::UInt => write!(f, "uint"),
422 PrimitiveType::UInt8 => write!(f, "uint8"),
423 PrimitiveType::UInt16 => write!(f, "uint16"),
424 PrimitiveType::UInt32 => write!(f, "uint32"),
425 PrimitiveType::UInt64 => write!(f, "uint64"),
426 PrimitiveType::Bool => write!(f, "bool"),
427 PrimitiveType::Byte => write!(f, "byte"),
428 PrimitiveType::Address => write!(f, "Address"),
429 }
430 }
431}
432
433/// The length of a fixed-size array type: an integer literal or a reference to
434/// a declared integer `const`. Folded to a count by `tast`
435/// (`tast::ArrayLen`).
436#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
437pub enum ArraySize {
438 /// An integer literal, e.g. `byte[1024]`.
439 Lit(u64),
440 /// A reference to a declared `const`, e.g. `byte[PACKET_BUFFER_SIZE]`.
441 Named(String),
442}
443
444impl Display for ArraySize {
445 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
446 match self {
447 ArraySize::Lit(n) => write!(f, "{n}"),
448 ArraySize::Named(name) => write!(f, "{name}"),
449 }
450 }
451}
452
453/// A complete type in Fiducia — primitive, named struct, or fixed-size array.
454///
455/// Pointer types (`ptr<T>`) are intentionally excluded from the Fiducia type
456/// system. All memory access goes through named, declared mappings.
457#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
458pub enum Type {
459 /// A primitive type like `int32`, `bool`, `byte`, or `Address`.
460 Primitive(PrimitiveType),
461 /// A named struct type.
462 Struct(String),
463 /// A fixed-size array `T[N]` — `N` contiguous elements of `T`. `N` is a
464 /// compile-time constant (literal or declared `const`), so `sizeof` stays
465 /// statically computable (`sizeof(T[N]) = N * sizeof(T)`).
466 Array {
467 /// Element type.
468 elem: Box<Type>,
469 /// Element count.
470 size: ArraySize,
471 },
472}
473
474impl Display for Type {
475 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
476 match self {
477 Type::Primitive(prim) => write!(f, "{prim}"),
478 Type::Struct(name) => write!(f, "{name}"),
479 Type::Array { elem, size } => write!(f, "{elem}[{size}]"),
480 }
481 }
482}