1use std::cell::RefCell;
4use std::rc::Rc;
5
6use crate::interpreter::RuntimeValue;
7
8use super::compare::values_equal;
9
10fn ascii_char_text(b: u8) -> Rc<String> {
17 debug_assert!(b < 128, "caller guarantees an ASCII byte");
18 thread_local! {
19 static CACHE: RefCell<[Option<Rc<String>>; 128]> =
20 RefCell::new(std::array::from_fn(|_| None));
21 }
22 CACHE.with(|c| {
23 c.borrow_mut()[b as usize]
24 .get_or_insert_with(|| Rc::new((b as char).to_string()))
25 .clone()
26 })
27}
28
29fn text_metrics(s: &Rc<String>) -> (bool, usize) {
38 thread_local! {
39 static CACHE: RefCell<Vec<(Rc<String>, usize, bool, usize)>> =
40 const { RefCell::new(Vec::new()) };
41 }
42 CACHE.with(|c| {
43 let mut c = c.borrow_mut();
44 let len = s.len();
45 if let Some(e) = c
46 .iter()
47 .find(|(rc, l, _, _)| *l == len && Rc::ptr_eq(rc, s))
48 {
49 return (e.2, e.3);
50 }
51 let ascii = s.is_ascii();
52 let char_len = if ascii { len } else { s.chars().count() };
53 if c.len() >= 8 {
54 c.remove(0);
55 }
56 c.push((s.clone(), len, ascii, char_len));
57 (ascii, char_len)
58 })
59}
60
61pub fn text_is_ascii(s: &Rc<String>) -> bool {
69 text_metrics(s).0
70}
71
72fn resolve_index(i: i64, len: usize) -> Result<usize, String> {
74 logicaffeine_data::logos_offset(i, len).ok_or_else(|| {
75 crate::semantics::failcode::message(
76 crate::semantics::failcode::FailCode::IndexOutOfBounds.code(),
77 i,
78 )
79 })
80}
81
82pub fn index_get(coll: &RuntimeValue, idx: &RuntimeValue) -> Result<RuntimeValue, String> {
85 match (coll, idx) {
86 (RuntimeValue::List(items), RuntimeValue::Int(i)) => {
87 let items = items.borrow();
88 let idx = resolve_index(*i, items.len())?;
89 Ok(items.get(idx).expect("bounds checked above"))
90 }
91 (RuntimeValue::Tuple(items), RuntimeValue::Int(i)) => {
92 let idx = resolve_index(*i, items.len())?;
93 Ok(items[idx].clone())
94 }
95 (RuntimeValue::Text(s), RuntimeValue::Int(i)) => {
96 let i = *i;
97 let bytes = s.as_bytes();
102 let (ascii, char_len) = text_metrics(s);
106 if i >= 1 && (i as usize) <= bytes.len() && ascii {
107 return Ok(RuntimeValue::Text(ascii_char_text(bytes[i as usize - 1])));
108 }
109 let idx = resolve_index(i, char_len)?;
110 Ok(RuntimeValue::Text(Rc::new(
111 s.chars().nth(idx).unwrap().to_string(),
112 )))
113 }
114 (RuntimeValue::Map(map), key) => {
115 let map = map.borrow();
116 match map.get(key) {
117 Some(val) => Ok(val.clone()),
118 None => Err(logicaffeine_data::failure::key_not_found(
119 key.to_display_string().as_str(),
120 )),
121 }
122 }
123 (RuntimeValue::Crdt(c), key)
125 if matches!(&*c.borrow(), crate::semantics::crdt::CrdtValue::Map(_)) =>
126 {
127 c.borrow().map_get(key)
128 }
129 (RuntimeValue::Struct(s), RuntimeValue::Text(field)) => {
131 match s.fields.get(field.as_str()) {
132 Some(val) => Ok(val.clone()),
133 None => Err(format!("Struct has no field '{}'", field)),
134 }
135 }
136 _ => Err(format!(
137 "Cannot index {} with {}",
138 coll.type_name(),
139 idx.type_name()
140 )),
141 }
142}
143
144pub fn index_set(
147 coll: &RuntimeValue,
148 idx: &RuntimeValue,
149 value: RuntimeValue,
150) -> Result<(), String> {
151 match (coll, idx) {
152 (RuntimeValue::List(items), RuntimeValue::Int(n)) => {
153 let mut items = items.borrow_mut();
154 let idx = resolve_index(*n, items.len())?;
155 items.set(idx, value);
156 Ok(())
157 }
158 (RuntimeValue::Map(map), key) => {
159 assert_hashable_key(key)?;
160 map.borrow_mut().insert(key.clone(), value);
161 Ok(())
162 }
163 (RuntimeValue::Crdt(c), key)
165 if matches!(&*c.borrow(), crate::semantics::crdt::CrdtValue::Map(_)) =>
166 {
167 c.borrow_mut().map_put(key, &value)
168 }
169 (RuntimeValue::List(_), _) => Err("List index must be an integer".to_string()),
170 _ => Err(format!("Cannot index into {}", coll.type_name())),
171 }
172}
173
174pub fn assert_hashable_key(key: &RuntimeValue) -> Result<(), String> {
179 match key {
180 RuntimeValue::List(_) | RuntimeValue::Set(_) | RuntimeValue::Map(_) => Err(format!(
181 "a {} cannot be a Map key — it is mutable, and mutating a live key \
182 would corrupt the map (use a Tuple of its values instead)",
183 key.type_name()
184 )),
185 RuntimeValue::Tuple(items) => {
186 for item in items.iter() {
187 assert_hashable_key(item)?;
188 }
189 Ok(())
190 }
191 RuntimeValue::Struct(s) => {
192 for value in s.fields.values() {
193 assert_hashable_key(value)?;
194 }
195 Ok(())
196 }
197 _ => Ok(()),
198 }
199}
200
201pub fn slice(
204 coll: &RuntimeValue,
205 start: &RuntimeValue,
206 end: &RuntimeValue,
207) -> Result<RuntimeValue, String> {
208 match (coll, start, end) {
209 (RuntimeValue::List(items), RuntimeValue::Int(s), RuntimeValue::Int(e)) => {
210 let items = items.borrow();
211 let range = logicaffeine_data::logos_slice_range(*s, *e, items.len());
212 let payload = if range.is_empty() {
213 crate::interpreter::ListRepr::Boxed(Vec::new())
214 } else {
215 items.slice(range.start, range.end - 1)
216 };
217 Ok(RuntimeValue::List(Rc::new(RefCell::new(payload))))
218 }
219 _ => Err("Slice requires List and Int indices".to_string()),
220 }
221}
222
223pub fn length_of(coll: &RuntimeValue) -> Result<RuntimeValue, String> {
226 match coll {
227 RuntimeValue::List(items) => Ok(RuntimeValue::Int(items.borrow().len() as i64)),
228 RuntimeValue::Tuple(items) => Ok(RuntimeValue::Int(items.len() as i64)),
229 RuntimeValue::Set(items) => Ok(RuntimeValue::Int(items.borrow().len() as i64)),
230 RuntimeValue::Text(s) => Ok(RuntimeValue::Int(s.len() as i64)),
231 RuntimeValue::Map(map) => Ok(RuntimeValue::Int(map.borrow().len() as i64)),
232 RuntimeValue::Crdt(c) => Ok(RuntimeValue::Int(c.borrow().len() as i64)),
233 _ => Err(format!("Cannot get length of {}", coll.type_name())),
234 }
235}
236
237pub fn contains(coll: &RuntimeValue, val: &RuntimeValue) -> Result<RuntimeValue, String> {
240 match coll {
241 RuntimeValue::List(items) => Ok(RuntimeValue::Bool(items.borrow().contains(val))),
242 RuntimeValue::Set(items) => {
243 let items = items.borrow();
244 let found = items.iter().any(|item| values_equal(item, val));
245 Ok(RuntimeValue::Bool(found))
246 }
247 RuntimeValue::Map(entries) => Ok(RuntimeValue::Bool(entries.borrow().contains_key(val))),
248 RuntimeValue::Text(s) => {
249 if let RuntimeValue::Text(needle) = val {
250 Ok(RuntimeValue::Bool(s.contains(needle.as_str())))
251 } else if let RuntimeValue::Char(c) = val {
252 Ok(RuntimeValue::Bool(s.contains(*c)))
253 } else {
254 Err(format!("Cannot check if Text contains {}", val.type_name()))
255 }
256 }
257 RuntimeValue::Crdt(c) => Ok(RuntimeValue::Bool(c.borrow().contains(val)?)),
258 _ => Err(format!("Cannot check contains on {}", coll.type_name())),
259 }
260}
261
262pub fn union(left: &RuntimeValue, right: &RuntimeValue) -> Result<RuntimeValue, String> {
264 match (left, right) {
265 (RuntimeValue::Set(a), RuntimeValue::Set(b)) => {
266 let a = a.borrow();
267 let b = b.borrow();
268 let mut result = a.clone();
269 for item in b.iter() {
270 if !result.iter().any(|x| values_equal(x, item)) {
271 result.push(item.clone());
272 }
273 }
274 Ok(RuntimeValue::Set(Rc::new(RefCell::new(result))))
275 }
276 _ => Err(format!(
277 "Cannot union {} and {}",
278 left.type_name(),
279 right.type_name()
280 )),
281 }
282}
283
284pub fn intersection(left: &RuntimeValue, right: &RuntimeValue) -> Result<RuntimeValue, String> {
286 match (left, right) {
287 (RuntimeValue::Set(a), RuntimeValue::Set(b)) => {
288 let a = a.borrow();
289 let b = b.borrow();
290 let result: Vec<RuntimeValue> = a
291 .iter()
292 .filter(|item| b.iter().any(|x| values_equal(x, item)))
293 .cloned()
294 .collect();
295 Ok(RuntimeValue::Set(Rc::new(RefCell::new(result))))
296 }
297 _ => Err(format!(
298 "Cannot intersect {} and {}",
299 left.type_name(),
300 right.type_name()
301 )),
302 }
303}
304
305pub fn range(start: &RuntimeValue, end: &RuntimeValue) -> Result<RuntimeValue, String> {
307 match (start, end) {
308 (RuntimeValue::Int(s), RuntimeValue::Int(e)) => {
309 let range: Vec<i64> = (*s..=*e).collect();
310 Ok(RuntimeValue::List(Rc::new(RefCell::new(
311 crate::interpreter::ListRepr::Ints(range),
312 ))))
313 }
314 _ => Err("Range requires Int bounds".to_string()),
315 }
316}
317
318pub fn iteration_snapshot(v: &RuntimeValue) -> Result<Vec<RuntimeValue>, String> {
325 match v {
326 RuntimeValue::List(list) => Ok(list.borrow().to_values()),
327 RuntimeValue::Set(set) => Ok(set.borrow().clone()),
328 RuntimeValue::Text(s) => Ok(s
329 .chars()
330 .map(|c| RuntimeValue::Text(Rc::new(c.to_string())))
331 .collect()),
332 RuntimeValue::Map(map) => Ok(map
333 .borrow()
334 .iter()
335 .map(|(k, v)| RuntimeValue::Tuple(Rc::new(vec![k.clone(), v.clone()])))
336 .collect()),
337 RuntimeValue::Crdt(c) => {
338 use crate::semantics::crdt::CrdtKind;
339 let c = c.borrow();
340 match c.crdt_kind() {
341 CrdtKind::Set | CrdtKind::SetRemoveWins | CrdtKind::Seq | CrdtKind::Map => {
342 Ok(c.to_runtime_vec())
343 }
344 CrdtKind::Register | CrdtKind::Counter | CrdtKind::PnCounter => {
345 Err(format!("Cannot iterate over {}", v.type_name()))
346 }
347 }
348 }
349 _ => Err(format!("Cannot iterate over {}", v.type_name())),
350 }
351}
352
353pub fn push_to_struct_field(
356 obj: &RuntimeValue,
357 field_name: &str,
358 val: RuntimeValue,
359) -> Result<(), String> {
360 if let RuntimeValue::Struct(s) = obj {
361 if let Some(RuntimeValue::List(items)) = s.fields.get(field_name) {
362 items.borrow_mut().push(val);
363 Ok(())
364 } else {
365 Err(format!("Field '{}' is not a List", field_name))
366 }
367 } else {
368 Err("Cannot push to field of non-struct".to_string())
369 }
370}
371
372thread_local! {
373 static FORCE_REFERENCE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
383}
384
385pub struct ReferenceScope;
388
389impl ReferenceScope {
390 pub fn enter() -> Self {
391 FORCE_REFERENCE.with(|c| c.set(c.get() + 1));
392 ReferenceScope
393 }
394}
395
396impl Drop for ReferenceScope {
397 fn drop(&mut self) {
398 FORCE_REFERENCE.with(|c| c.set(c.get().saturating_sub(1)));
399 }
400}
401
402pub fn with_reference_semantics<T>(f: impl FnOnce() -> T) -> T {
404 let _g = ReferenceScope::enter();
405 f()
406}
407
408pub fn reference_scope_active() -> bool {
412 FORCE_REFERENCE.with(|c| c.get() > 0)
413}
414
415pub fn value_semantics_enabled() -> bool {
423 use std::sync::OnceLock;
424 static ON: OnceLock<bool> = OnceLock::new();
425 if reference_scope_active() {
426 return false;
427 }
428 *ON.get_or_init(|| std::env::var("LOGOS_VALUE_SEMANTICS").as_deref() != Ok("0"))
429}
430
431pub fn list_push(coll: &RuntimeValue, value: RuntimeValue) -> Result<(), String> {
433 match coll {
434 RuntimeValue::List(items) => {
435 items.borrow_mut().push(value);
436 Ok(())
437 }
438 _ => Err("Can only push to a List".to_string()),
439 }
440}
441
442pub fn list_pop(coll: &RuntimeValue) -> Result<RuntimeValue, String> {
445 match coll {
446 RuntimeValue::List(items) => Ok(items.borrow_mut().pop().unwrap_or(RuntimeValue::Nothing)),
447 _ => Err("Can only pop from a List".to_string()),
448 }
449}
450
451pub fn set_add(coll: &RuntimeValue, value: RuntimeValue) -> Result<(), String> {
453 match coll {
454 RuntimeValue::Set(items) => {
455 let already_present = items.borrow().iter().any(|x| values_equal(x, &value));
456 if !already_present {
457 items.borrow_mut().push(value);
458 }
459 Ok(())
460 }
461 RuntimeValue::Crdt(c) => c.borrow_mut().insert(&value),
462 _ => Err("Can only add to a Set".to_string()),
463 }
464}
465
466pub fn remove_from(coll: &RuntimeValue, value: &RuntimeValue) -> Result<(), String> {
468 match coll {
469 RuntimeValue::Set(items) => {
470 items.borrow_mut().retain(|x| !values_equal(x, value));
471 Ok(())
472 }
473 RuntimeValue::Map(map) => {
474 map.borrow_mut().shift_remove(value);
475 Ok(())
476 }
477 RuntimeValue::Crdt(c) => c.borrow_mut().remove(value),
478 _ => Err("Can only remove from a Set or Map".to_string()),
479 }
480}
481
482#[cfg(test)]
483#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/collections/tests.rs"]
484mod tests;
485
486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
489pub enum IntegerPlace {
490 ListRead,
491 ListStore,
492 Text,
493 Tuple,
494 Range,
495 Slice,
496}
497
498impl IntegerPlace {
499 pub const ALL: [IntegerPlace; 6] = [
501 IntegerPlace::ListRead,
502 IntegerPlace::ListStore,
503 IntegerPlace::Text,
504 IntegerPlace::Tuple,
505 IntegerPlace::Range,
506 IntegerPlace::Slice,
507 ];
508
509 pub fn code(self) -> i32 {
511 IntegerPlace::ALL.iter().position(|p| *p == self).expect("every place is listed") as i32
512 }
513
514 pub fn of_code(code: i32) -> Option<IntegerPlace> {
516 usize::try_from(code).ok().and_then(|i| IntegerPlace::ALL.get(i).copied())
517 }
518}
519
520pub fn integer_place_refusals(place: IntegerPlace) -> (String, String) {
523 use crate::semantics::failcode::{message, FailCode};
524 let list = || RuntimeValue::List(Rc::new(RefCell::new(crate::interpreter::ListRepr::from_values(Vec::new()))));
525 let pair = || RuntimeValue::Tuple(Rc::new(vec![RuntimeValue::Int(1), RuntimeValue::Int(2)]));
526 let fraction = || {
527 RuntimeValue::from_rational(logicaffeine_base::Rational::from_ratio_i64(1, 2).expect("a nonzero denominator"))
528 };
529 let past_word = || RuntimeValue::from_bigint(logicaffeine_base::BigInt::from_i64(2).pow(70));
530 let refused = |r: Result<RuntimeValue, String>| r.expect_err("the VM refuses it");
531 let past = |code: FailCode| message(code.code(), 0);
532 match place {
533 IntegerPlace::ListRead => (past(FailCode::ListIndexTooWide), refused(index_get(&list(), &fraction()))),
534 IntegerPlace::ListStore => (
535 past(FailCode::ListStoreIndexTooWide),
536 index_set(&list(), &fraction(), RuntimeValue::Int(0)).expect_err("the VM refuses it"),
537 ),
538 IntegerPlace::Text => (
539 past(FailCode::TextIndexTooWide),
540 refused(index_get(&RuntimeValue::Text(Rc::new("abc".to_string())), &fraction())),
541 ),
542 IntegerPlace::Tuple => (refused(index_get(&pair(), &past_word())), refused(index_get(&pair(), &fraction()))),
543 IntegerPlace::Range => (
544 refused(range(&RuntimeValue::Int(1), &past_word())),
545 refused(range(&RuntimeValue::Int(1), &fraction())),
546 ),
547 IntegerPlace::Slice => (
548 refused(slice(&list(), &past_word(), &RuntimeValue::Int(1))),
549 refused(slice(&list(), &fraction(), &RuntimeValue::Int(1))),
550 ),
551 }
552}