Skip to main content

logicaffeine_data/
types.rs

1//! Core runtime type definitions.
2//!
3//! This module defines the primitive types used by LOGOS programs at runtime.
4//! These are type aliases that map LOGOS types to their Rust equivalents.
5//!
6//! ## Type Mappings
7//!
8//! | LOGOS Type | Rust Type | Description |
9//! |------------|-----------|-------------|
10//! | `Nat` | `u64` | Natural numbers (non-negative) |
11//! | `Int` | `i64` | Signed integers |
12//! | `Real` | `f64` | Floating-point numbers |
13//! | `Text` | `String` | UTF-8 strings |
14//! | `Bool` | `bool` | Boolean values |
15//! | `Unit` | `()` | The unit type |
16//! | `Char` | `char` | Unicode scalar values |
17//! | `Byte` | `u8` | Raw bytes |
18//! | `Seq<T>` | `Vec<T>` | Ordered sequences |
19//! | `Set<T>` | `HashSet<T>` | Unordered unique elements |
20//! | `Map<K,V>` | `HashMap<K,V>` | Key-value mappings |
21
22use std::hash::Hash;
23
24/// Non-negative integers. Maps to Peano `Nat` in the kernel.
25pub type Nat = u64;
26/// Signed integers.
27pub type Int = i64;
28/// IEEE 754 floating-point numbers.
29pub type Real = f64;
30/// UTF-8 encoded text strings.
31pub type Text = String;
32/// Boolean truth values.
33pub type Bool = bool;
34/// The unit type (single value).
35pub type Unit = ();
36/// Unicode scalar values.
37pub type Char = char;
38/// Raw bytes (0-255).
39pub type Byte = u8;
40
41/// Ordered sequences (lists).
42pub type Seq<T> = Vec<T>;
43
44/// Key-value mappings with hash-based lookup.
45pub type Map<K, V> = std::collections::HashMap<K, V>;
46
47/// Unordered collections of unique elements.
48pub type Set<T> = std::collections::HashSet<T>;
49
50/// Unified containment testing for all collection types.
51///
52/// This trait provides a consistent `logos_contains` method across Logos's
53/// collection types, abstracting over the different containment semantics
54/// of vectors (by value), sets (by membership), maps (by key), and
55/// strings (by substring or character).
56///
57/// # Implementations
58///
59/// - [`Vec<T>`]: Tests if the vector contains an element equal to the value
60/// - [`HashSet<T>`]: Tests if the element is a member of the set
61/// - [`HashMap<K, V>`]: Tests if a key exists in the map
62/// - [`String`]: Tests for substring (`&str`) or character (`char`) presence
63/// - [`ORSet<T, B>`]: Tests if the element is in the CRDT set
64///
65/// # Examples
66///
67/// ```
68/// use logicaffeine_data::LogosContains;
69///
70/// // Vector: contains by value equality
71/// let v = vec![1, 2, 3];
72/// assert!(v.logos_contains(&2));
73/// assert!(!v.logos_contains(&5));
74///
75/// // String: contains by substring
76/// let s = String::from("hello world");
77/// assert!(s.logos_contains(&"world"));
78///
79/// // String: contains by character
80/// assert!(s.logos_contains(&'o'));
81/// ```
82pub trait LogosContains<T> {
83    /// Check if this collection contains the given value.
84    fn logos_contains(&self, value: &T) -> bool;
85}
86
87impl<T: PartialEq> LogosContains<T> for Vec<T> {
88    #[inline(always)]
89    fn logos_contains(&self, value: &T) -> bool {
90        self.contains(value)
91    }
92}
93
94impl<T: Eq + Hash> LogosContains<T> for std::collections::HashSet<T> {
95    #[inline(always)]
96    fn logos_contains(&self, value: &T) -> bool {
97        self.contains(value)
98    }
99}
100
101impl<K: Eq + Hash, V> LogosContains<K> for std::collections::HashMap<K, V> {
102    #[inline(always)]
103    fn logos_contains(&self, key: &K) -> bool {
104        self.contains_key(key)
105    }
106}
107
108impl LogosContains<&str> for String {
109    #[inline(always)]
110    fn logos_contains(&self, value: &&str) -> bool {
111        self.contains(*value)
112    }
113}
114
115impl LogosContains<String> for String {
116    #[inline(always)]
117    fn logos_contains(&self, value: &String) -> bool {
118        self.contains(value.as_str())
119    }
120}
121
122impl LogosContains<char> for String {
123    #[inline(always)]
124    fn logos_contains(&self, value: &char) -> bool {
125        self.contains(*value)
126    }
127}
128
129impl<T: Eq + Hash + Clone, B: crate::crdt::SetBias> LogosContains<T>
130    for crate::crdt::ORSet<T, B>
131{
132    #[inline(always)]
133    fn logos_contains(&self, value: &T) -> bool {
134        self.contains(value)
135    }
136}
137
138/// Dynamic value type for heterogeneous collections.
139///
140/// `Value` enables tuples and other heterogeneous data structures in Logos.
141/// It supports basic arithmetic between compatible types and provides
142/// runtime type coercion where sensible.
143///
144/// # Variants
145///
146/// - `Int(i64)` - Integer values
147/// - `Float(f64)` - Floating-point values
148/// - `Bool(bool)` - Boolean values
149/// - `Text(String)` - String values
150/// - `Char(char)` - Single character values
151/// - `Nothing` - Unit/null value
152///
153/// # Arithmetic
154///
155/// Arithmetic operations are supported between numeric types:
156/// - `Int op Int` → `Int`
157/// - `Float op Float` → `Float`
158/// - `Int op Float` or `Float op Int` → `Float` (promotion)
159/// - `Text + Text` → `Text` (concatenation)
160///
161/// # Panics
162///
163/// Arithmetic on incompatible variants panics at runtime.
164///
165/// # Examples
166///
167/// ```
168/// use logicaffeine_data::Value;
169///
170/// let a = Value::Int(10);
171/// let b = Value::Int(3);
172/// assert_eq!(a + b, Value::Int(13));
173///
174/// let x = Value::Float(2.5);
175/// let y = Value::Int(2);
176/// assert_eq!(x * y, Value::Float(5.0));
177/// ```
178#[derive(Clone, Debug, PartialEq)]
179pub enum Value {
180    /// Integer values.
181    Int(i64),
182    /// Floating-point values.
183    Float(f64),
184    /// Boolean values.
185    Bool(bool),
186    /// String values.
187    Text(String),
188    /// Single character values.
189    Char(char),
190    /// Unit/null value.
191    Nothing,
192}
193
194impl std::fmt::Display for Value {
195    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196        match self {
197            Value::Int(n) => write!(f, "{}", n),
198            Value::Float(n) => write!(f, "{}", n),
199            Value::Bool(b) => write!(f, "{}", b),
200            Value::Text(s) => write!(f, "{}", s),
201            Value::Char(c) => write!(f, "{}", c),
202            Value::Nothing => write!(f, "nothing"),
203        }
204    }
205}
206
207// Conversion traits for Value
208impl From<i64> for Value {
209    fn from(n: i64) -> Self { Value::Int(n) }
210}
211
212impl From<f64> for Value {
213    fn from(n: f64) -> Self { Value::Float(n) }
214}
215
216impl From<bool> for Value {
217    fn from(b: bool) -> Self { Value::Bool(b) }
218}
219
220impl From<String> for Value {
221    fn from(s: String) -> Self { Value::Text(s) }
222}
223
224impl From<&str> for Value {
225    fn from(s: &str) -> Self { Value::Text(s.to_string()) }
226}
227
228impl From<char> for Value {
229    fn from(c: char) -> Self { Value::Char(c) }
230}
231
232/// Tuple type: Vec of heterogeneous Values (uses LogosIndex from indexing module)
233pub type Tuple = Vec<Value>;
234
235// NOTE: Showable impl for Value is in logicaffeine_system (io module)
236// This crate (logicaffeine_data) has NO IO dependencies.
237
238// Arithmetic operations for Value
239impl std::ops::Add for Value {
240    type Output = Value;
241
242    #[inline]
243    fn add(self, other: Value) -> Value {
244        match (self, other) {
245            (Value::Int(a), Value::Int(b)) => Value::Int(a + b),
246            (Value::Float(a), Value::Float(b)) => Value::Float(a + b),
247            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 + b),
248            (Value::Float(a), Value::Int(b)) => Value::Float(a + b as f64),
249            (Value::Text(a), Value::Text(b)) => Value::Text(format!("{}{}", a, b)),
250            _ => panic!("Cannot add these value types"),
251        }
252    }
253}
254
255impl std::ops::Sub for Value {
256    type Output = Value;
257
258    #[inline]
259    fn sub(self, other: Value) -> Value {
260        match (self, other) {
261            (Value::Int(a), Value::Int(b)) => Value::Int(a - b),
262            (Value::Float(a), Value::Float(b)) => Value::Float(a - b),
263            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 - b),
264            (Value::Float(a), Value::Int(b)) => Value::Float(a - b as f64),
265            _ => panic!("Cannot subtract these value types"),
266        }
267    }
268}
269
270impl std::ops::Mul for Value {
271    type Output = Value;
272
273    #[inline]
274    fn mul(self, other: Value) -> Value {
275        match (self, other) {
276            (Value::Int(a), Value::Int(b)) => Value::Int(a * b),
277            (Value::Float(a), Value::Float(b)) => Value::Float(a * b),
278            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 * b),
279            (Value::Float(a), Value::Int(b)) => Value::Float(a * b as f64),
280            _ => panic!("Cannot multiply these value types"),
281        }
282    }
283}
284
285impl std::ops::Div for Value {
286    type Output = Value;
287
288    #[inline]
289    fn div(self, other: Value) -> Value {
290        match (self, other) {
291            (Value::Int(a), Value::Int(b)) => Value::Int(a / b),
292            (Value::Float(a), Value::Float(b)) => Value::Float(a / b),
293            (Value::Int(a), Value::Float(b)) => Value::Float(a as f64 / b),
294            (Value::Float(a), Value::Int(b)) => Value::Float(a / b as f64),
295            _ => panic!("Cannot divide these value types"),
296        }
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    #[test]
305    fn value_int_arithmetic() {
306        assert_eq!(Value::Int(10) + Value::Int(3), Value::Int(13));
307        assert_eq!(Value::Int(10) - Value::Int(3), Value::Int(7));
308        assert_eq!(Value::Int(10) * Value::Int(3), Value::Int(30));
309        assert_eq!(Value::Int(10) / Value::Int(3), Value::Int(3));
310    }
311
312    #[test]
313    fn value_float_arithmetic() {
314        assert_eq!(Value::Float(2.5) + Value::Float(1.5), Value::Float(4.0));
315        assert_eq!(Value::Float(5.0) - Value::Float(1.5), Value::Float(3.5));
316        assert_eq!(Value::Float(2.0) * Value::Float(3.0), Value::Float(6.0));
317        assert_eq!(Value::Float(7.0) / Value::Float(2.0), Value::Float(3.5));
318    }
319
320    #[test]
321    fn value_cross_type_promotion() {
322        assert_eq!(Value::Int(2) + Value::Float(1.5), Value::Float(3.5));
323        assert_eq!(Value::Float(2.5) + Value::Int(2), Value::Float(4.5));
324        assert_eq!(Value::Int(3) * Value::Float(2.0), Value::Float(6.0));
325        assert_eq!(Value::Float(6.0) / Value::Int(2), Value::Float(3.0));
326    }
327
328    #[test]
329    fn value_text_concat() {
330        assert_eq!(
331            Value::Text("hello".to_string()) + Value::Text(" world".to_string()),
332            Value::Text("hello world".to_string())
333        );
334    }
335
336    #[test]
337    #[should_panic(expected = "divide by zero")]
338    fn value_div_by_zero_panics() {
339        let _ = Value::Int(1) / Value::Int(0);
340    }
341
342    #[test]
343    #[should_panic(expected = "Cannot add")]
344    fn value_incompatible_types_panic() {
345        let _ = Value::Bool(true) + Value::Int(1);
346    }
347
348    #[test]
349    fn value_display() {
350        assert_eq!(format!("{}", Value::Int(42)), "42");
351        assert_eq!(format!("{}", Value::Float(3.14)), "3.14");
352        assert_eq!(format!("{}", Value::Bool(true)), "true");
353        assert_eq!(format!("{}", Value::Text("hi".to_string())), "hi");
354        assert_eq!(format!("{}", Value::Char('a')), "a");
355        assert_eq!(format!("{}", Value::Nothing), "nothing");
356    }
357
358    #[test]
359    fn value_from_conversions() {
360        assert_eq!(Value::from(42i64), Value::Int(42));
361        assert_eq!(Value::from(3.14f64), Value::Float(3.14));
362        assert_eq!(Value::from(true), Value::Bool(true));
363        assert_eq!(Value::from("hello"), Value::Text("hello".to_string()));
364        assert_eq!(Value::from("hello".to_string()), Value::Text("hello".to_string()));
365        assert_eq!(Value::from('x'), Value::Char('x'));
366    }
367}